1
0
Fork 0
mirror of https://github.com/Yetangitu/ampache synced 2025-10-04 10:19:25 +02:00

Replaced almost every dba::query to dba::read or dba::write.

This commit is contained in:
dipsol 2009-12-14 08:06:20 +00:00
parent 9b3232ba29
commit a7838e2a13
20 changed files with 2463 additions and 2463 deletions

View file

@ -58,7 +58,7 @@ if ($where) $where = "($where) AND catalog_type='local'";
else $where = "catalog_type='local'"; else $where = "catalog_type='local'";
$sql = "SELECT id FROM catalog"; $sql = "SELECT id FROM catalog";
if ($where) $sql .= " WHERE $where"; if ($where) $sql .= " WHERE $where";
$db_results = Dba::query($sql); $db_results = Dba::read($sql);
ob_start("ob_html_strip",'4096',true); ob_start("ob_html_strip",'4096',true);

View file

@ -30,28 +30,28 @@ $debug = true;
define('NO_SESSION','1'); define('NO_SESSION','1');
$path = dirname(__FILE__); $path = dirname(__FILE__);
$prefix = realpath($path . '/../'); $prefix = realpath($path . '/../');
require_once $prefix . '/lib/init.php'; require_once $prefix . '/lib/init.php';
if ($debug) { echo _("DEBUG ENABLED WILL NOT DELETE FILES!"); echo "\n"; } if ($debug) { echo _("DEBUG ENABLED WILL NOT DELETE FILES!"); echo "\n"; }
/* Get a list of filenames */ /* Get a list of filenames */
$sql = "SELECT `id`,`file` FROM song WHERE enabled='0'"; $sql = "SELECT `id`,`file` FROM song WHERE enabled='0'";
$db_results = Dba::query($sql); $db_results = Dba::read($sql);
while ($row = Dba::fetch_assoc($db_results)) { while ($row = Dba::fetch_assoc($db_results)) {
if ($debug) { if ($debug) {
printf (_('Would Delete: %s'), $row['file']); printf (_('Would Delete: %s'), $row['file']);
echo "\n"; echo "\n";
} }
else { else {
printf (_('Deleting: %s'), $row['file']); printf (_('Deleting: %s'), $row['file']);
echo "\n"; echo "\n";
unlink($row['file']); unlink($row['file']);
$sql = "DELETE FROM `song` WHERE `id`='" . Dba::escape($row['id']) . "'"; $sql = "DELETE FROM `song` WHERE `id`='" . Dba::escape($row['id']) . "'";
$del_results = Dba::query($sql); $del_results = Dba::write($sql);
} }
} // end while } // end while
?> ?>

View file

@ -20,14 +20,14 @@
*/ */
define('NO_SESSION','1'); define('NO_SESSION','1');
$path = dirname(__FILE__); $path = dirname(__FILE__);
$prefix = realpath($path . '/../'); $prefix = realpath($path . '/../');
require_once $prefix . '/lib/init.php'; require_once $prefix . '/lib/init.php';
ob_end_clean(); ob_end_clean();
/* /*
* Pull the root path of your catalogs one by one * Pull the root path of your catalogs one by one
* and then do a directory sweep and check all of the files * and then do a directory sweep and check all of the files
* that would be cataloged and see if they have the correct charset * that would be cataloged and see if they have the correct charset
* if they don't prompt for a rename, unless $i_am_crazy is true then just * if they don't prompt for a rename, unless $i_am_crazy is true then just
@ -35,7 +35,7 @@ ob_end_clean();
*/ */
// If set to true / 1 then it will not prompt! // If set to true / 1 then it will not prompt!
//$GLOBALS['i_am_crazy'] = true; //$GLOBALS['i_am_crazy'] = true;
if (!function_exists('iconv')) { if (!function_exists('iconv')) {
echo _("ERROR: Iconv required for this functionality, quiting"); echo _("ERROR: Iconv required for this functionality, quiting");
@ -46,15 +46,15 @@ if (!function_exists('iconv')) {
// Attempt to figure out what the System Charset is // Attempt to figure out what the System Charset is
$source_encoding = iconv_get_encoding('output_encoding'); $source_encoding = iconv_get_encoding('output_encoding');
// Attempt a simple translation // Attempt a simple translation
$string = sprintf(_('%s For the Love of Music'), iconv(Config::get('site_charset'),Config::get('site_charset'))); $string = sprintf(_('%s For the Love of Music'), iconv(Config::get('site_charset'),Config::get('site_charset')));
echo _('Testing Basic Translation, the two strings below should look the same'); echo _('Testing Basic Translation, the two strings below should look the same');
echo "\n"; echo "\n";
echo _('Original: For the Love of Music'); echo _('Original: For the Love of Music');
echo "\n"; echo "\n";
printf (_('Translated: %s'), $string); printf (_('Translated: %s'), $string);
echo "\n"; echo "\n";
echo "---------------------------------------------------------------------\n"; echo "---------------------------------------------------------------------\n";
printf (_('Input Charset (%s):'), $source_encoding); printf (_('Input Charset (%s):'), $source_encoding);
$input = trim(fgets(STDIN)); $input = trim(fgets(STDIN));
@ -62,14 +62,14 @@ if (strlen($input) > 0) { $source_encoding = trim($input); }
printf (_('Using %s as source character set'), $source_encoding); printf (_('Using %s as source character set'), $source_encoding);
echo "\n"; echo "\n";
$sql = "SELECT * FROM `catalog` WHERE `catalog_type`='local'"; $sql = "SELECT * FROM `catalog` WHERE `catalog_type`='local'";
$db_results = Dba::query($sql); $db_results = Dba::read($sql);
while ($row = Dba::fetch_assoc($db_results)) { while ($row = Dba::fetch_assoc($db_results)) {
printf(_('Checking %s (%s)'), $row['name'], $row['path']); printf(_('Checking %s (%s)'), $row['name'], $row['path']);
echo "\n"; echo "\n";
charset_directory_correct($row['path']); charset_directory_correct($row['path']);
} // end of the catalogs } // end of the catalogs
@ -81,11 +81,11 @@ echo "\n";
**************************************************/ **************************************************/
/** /**
* charset_directory_correct * charset_directory_correct
* This function calls its self recursivly * This function calls its self recursivly
* and corrects all of the non-matching filenames * and corrects all of the non-matching filenames
* it looks at the i_am_crazy var and if not set prompts for change * it looks at the i_am_crazy var and if not set prompts for change
*/ */
function charset_directory_correct($path) { function charset_directory_correct($path) {
// Correctly detect the slash we need to use here // Correctly detect the slash we need to use here
if (strstr($path,"/")) { if (strstr($path,"/")) {

View file

@ -20,8 +20,8 @@
*/ */
define('NO_SESSION','1'); define('NO_SESSION','1');
$path = dirname(__FILE__); $path = dirname(__FILE__);
$prefix = realpath($path . '/../'); $prefix = realpath($path . '/../');
require_once $prefix . '/lib/init.php'; require_once $prefix . '/lib/init.php';
$version = "1.0"; $version = "1.0";
@ -32,8 +32,8 @@ $allowexts = preg_split('/\|/', $exts);
if (count($GLOBALS['argv']) == '1') { if (count($GLOBALS['argv']) == '1') {
usage(); usage();
exit; exit;
} else { } else {
$filename = $GLOBALS['argv']['1']; $filename = $GLOBALS['argv']['1'];
$send_mail = $GLOBALS['argv']['2']; $send_mail = $GLOBALS['argv']['2'];
} }
@ -56,7 +56,7 @@ print "\n";
/* Attempt to figure out what catalog it comes from */ /* Attempt to figure out what catalog it comes from */
$sql = "SELECT `catalog`.`id` FROM `song` INNER JOIN `catalog` ON `song`.`catalog`=`catalog`.`id` WHERE `song`.`file` LIKE '%" . Dba::escape($filename) . "'"; $sql = "SELECT `catalog`.`id` FROM `song` INNER JOIN `catalog` ON `song`.`catalog`=`catalog`.`id` WHERE `song`.`file` LIKE '%" . Dba::escape($filename) . "'";
$db_results = Dba::query($sql); $db_results = Dba::read($sql);
$results = Dba::fetch_assoc($db_results); $results = Dba::fetch_assoc($db_results);
$catalog = new Catalog($results['id']); $catalog = new Catalog($results['id']);
@ -72,7 +72,7 @@ $results['file'] = $filename;
$key = vainfo::get_tag_type($results); $key = vainfo::get_tag_type($results);
$ampache_results = vainfo::clean_tag_info($results,$key,$filename); $ampache_results = vainfo::clean_tag_info($results,$key,$filename);
if ($send_mail) { if ($send_mail) {
$getid3_results = print_r($info,1); $getid3_results = print_r($info,1);
$amp_results = print_r($ampache_results,1); $amp_results = print_r($ampache_results,1);
$body = $getid3_results . "\n-----\n\n" . $amp_results; $body = $getid3_results . "\n-----\n\n" . $amp_results;

View file

@ -26,17 +26,17 @@
* tag information gathered and updated in ampache. Sort_Pattern defines the directory * tag information gathered and updated in ampache. Sort_Pattern defines the directory
* structure and rename_pattern defines the file pattern. This script should allow you * structure and rename_pattern defines the file pattern. This script should allow you
* to do both or neither. Oooh and allow you to sort with A,B,C,D prefix * to do both or neither. Oooh and allow you to sort with A,B,C,D prefix
* *
* Attempt 1 - Do each file one by one and satisfy the needs of each file by its self (this is going to be slow) * Attempt 1 - Do each file one by one and satisfy the needs of each file by its self (this is going to be slow)
* Cache information so we don't have to check for every file! * Cache information so we don't have to check for every file!
*/ */
/* Don't do anything just tell me what you would do */ /* Don't do anything just tell me what you would do */
//$test_mode = true; //$test_mode = true;
/* m(__)m */ /* m(__)m */
$alphabet_prefix = true; $alphabet_prefix = true;
define('NO_SESSION','1'); define('NO_SESSION','1');
$path = dirname(__FILE__); $path = dirname(__FILE__);
$prefix = realpath($path . '/../'); $prefix = realpath($path . '/../');
@ -47,7 +47,7 @@ ob_end_clean();
/* First Clean the catalog to we don't try to write anything we shouldn't */ /* First Clean the catalog to we don't try to write anything we shouldn't */
$sql = "SELECT `id` FROM `catalog` WHERE `catalog_type`='local'"; $sql = "SELECT `id` FROM `catalog` WHERE `catalog_type`='local'";
$db_results = Dba::query($sql); $db_results = Dba::read($sql);
$catalogs = array(); $catalogs = array();
@ -93,7 +93,7 @@ while ($r = Dba::fetch_row($db_results)) {
/************** FUNCTIONS *****************/ /************** FUNCTIONS *****************/
/** /**
* sort_find_home * sort_find_home
* Get the directory for this file from the catalog and the song info using the sort_pattern * Get the directory for this file from the catalog and the song info using the sort_pattern
* takes into account various artists and the alphabet_prefix * takes into account various artists and the alphabet_prefix
*/ */
function sort_find_home($song,$sort_pattern,$base) { function sort_find_home($song,$sort_pattern,$base) {
@ -144,9 +144,9 @@ function sort_find_home($song,$sort_pattern,$base) {
/** /**
* sort_element_name * sort_element_name
* gets the name of the %? in a yea.. too much beer * gets the name of the %? in a yea.. too much beer
*/ */
function sort_element_name($key) { function sort_element_name($key) {
switch ($key) { switch ($key) {
case '%t': case '%t':
@ -194,7 +194,7 @@ function sort_clean_name($string) {
/** /**
* sort_move_file * sort_move_file
* All this function does is, move the friggin file and then update the database * All this function does is, move the friggin file and then update the database
* We can't use the rename() function of PHP because it's functionality depends on the * We can't use the rename() function of PHP because it's functionality depends on the
* current phase of the moon, the alignment of the planets and my current BAL * current phase of the moon, the alignment of the planets and my current BAL
* Instead we cheeseball it and walk through the new dir structure and make * Instead we cheeseball it and walk through the new dir structure and make
@ -249,7 +249,7 @@ function sort_move_file($song,$fullname) {
echo "\n"; echo "\n";
$sql = "UPDATE song SET file='" . Dba::escape($fullname) . "' WHERE id='" . Dba::escape($song->id) . "'"; $sql = "UPDATE song SET file='" . Dba::escape($fullname) . "' WHERE id='" . Dba::escape($song->id) . "'";
echo "\tSQL: $sql\n"; echo "\tSQL: $sql\n";
flush(); flush();
} }
else { else {
@ -295,7 +295,7 @@ function sort_move_file($song,$fullname) {
/* Update the catalog */ /* Update the catalog */
$sql = "UPDATE song SET file='" . Dba::escape($fullname) . "' WHERE id='" . Dba::escape($song->id) . "'"; $sql = "UPDATE song SET file='" . Dba::escape($fullname) . "' WHERE id='" . Dba::escape($song->id) . "'";
$db_results = Dba::query($sql); $db_results = Dba::write($sql);
} // end else } // end else

View file

@ -22,10 +22,10 @@
class AmpacheMail { class AmpacheMail {
// The message, recipient and from // The message, recipient and from
public static $message; public static $message;
public static $recipient; public static $recipient;
public static $fromname; public static $fromname;
public static $subject; public static $subject;
public static $to; public static $to;
public static $fullname; public static $fullname;
public static $sender; public static $sender;
@ -34,7 +34,7 @@ class AmpacheMail {
* Constructor * Constructor
* This isn't used * This isn't used
*/ */
private function __construct($name) { private function __construct($name) {
// Rien a faire // Rien a faire
@ -45,34 +45,34 @@ class AmpacheMail {
* This returns an array of userid's for people who have e-mail addresses * This returns an array of userid's for people who have e-mail addresses
* based on the passed filter * based on the passed filter
*/ */
public static function get_users($filter) { public static function get_users($filter) {
switch ($filter) { switch ($filter) {
default: default:
case 'all': case 'all':
$sql = "SELECT * FROM `user` WHERE `email` IS NOT NULL"; $sql = "SELECT * FROM `user` WHERE `email` IS NOT NULL";
break; break;
case 'users': case 'users':
$sql = "SELECT * FROM `user` WHERE `access`='25' AND `email` IS NOT NULL"; $sql = "SELECT * FROM `user` WHERE `access`='25' AND `email` IS NOT NULL";
break; break;
case 'admins': case 'admins':
$sql = "SELECT * FROM `user` WHERE `access`='100' AND `email` IS NOT NULL"; $sql = "SELECT * FROM `user` WHERE `access`='100' AND `email` IS NOT NULL";
break ; break ;
case 'inactive': case 'inactive':
$inactive = time() - (30*86400); $inactive = time() - (30*86400);
$sql = "SELECT * FROM `user` WHERE `last_seen` <= '$inactive' AND `email` IS NOT NULL"; $sql = "SELECT * FROM `user` WHERE `last_seen` <= '$inactive' AND `email` IS NOT NULL";
break; break;
} // end filter switch } // end filter switch
$db_results = Dba::query($sql);
$results = array();
while ($row = Dba::fetch_assoc($db_results)) {
$results[] = array('id'=>$row['id'],'fullname'=>$row['fullname'],'email'=>$row['email']);
}
return $results; $db_results = Dba::read($sql);
$results = array();
while ($row = Dba::fetch_assoc($db_results)) {
$results[] = array('id'=>$row['id'],'fullname'=>$row['fullname'],'email'=>$row['email']);
}
return $results;
} // get_users } // get_users
@ -80,9 +80,9 @@ class AmpacheMail {
* add_statistics * add_statistics
* This should be run if we want to add some statistics to this e-mail, appends to self::$message * This should be run if we want to add some statistics to this e-mail, appends to self::$message
*/ */
public static function add_statistics($methods) { public static function add_statistics($methods) {
} // add_statistics } // add_statistics
@ -90,11 +90,11 @@ class AmpacheMail {
* send * send
* This actually sends the mail, how amazing * This actually sends the mail, how amazing
*/ */
public static function send() { public static function send() {
$mailtype = Config::get('mail_type'); $mailtype = Config::get('mail_type');
$mail = new PHPMailer(); $mail = new PHPMailer();
$mail->AddAddress(self::$to, self::$fullname); $mail->AddAddress(self::$to, self::$fullname);
$mail->CharSet = Config::get('site_charset'); $mail->CharSet = Config::get('site_charset');
$mail->Encoding = "base64"; $mail->Encoding = "base64";

View file

@ -21,42 +21,42 @@
/** /**
* database_object * database_object
* This is a general object that is extended by all of the basic * This is a general object that is extended by all of the basic
* database based objects in ampache. It attempts to do some standard * database based objects in ampache. It attempts to do some standard
* caching for all of the objects to cut down on the database calls * caching for all of the objects to cut down on the database calls
*/ */
abstract class database_object { abstract class database_object {
private static $object_cache = array(); private static $object_cache = array();
// Statistics for debugging // Statistics for debugging
public static $cache_hit = 0; public static $cache_hit = 0;
private static $_enabled = false; private static $_enabled = false;
/** /**
* get_info * get_info
* retrieves the info from the database and puts it in the cache * retrieves the info from the database and puts it in the cache
*/ */
public function get_info($id,$table_name='') { public function get_info($id,$table_name='') {
$table_name = $table_name ? Dba::escape($table_name) : Dba::escape(strtolower(get_class($this))); $table_name = $table_name ? Dba::escape($table_name) : Dba::escape(strtolower(get_class($this)));
// Make sure we've got a real id // Make sure we've got a real id
if (!is_numeric($id)) { return array(); } if (!is_numeric($id)) { return array(); }
if (self::is_cached($table_name,$id)) { if (self::is_cached($table_name,$id)) {
return self::get_from_cache($table_name,$id); return self::get_from_cache($table_name,$id);
} }
$sql = "SELECT * FROM `$table_name` WHERE `id`='$id'"; $sql = "SELECT * FROM `$table_name` WHERE `id`='$id'";
$db_results = Dba::query($sql); $db_results = Dba::read($sql);
if (!$db_results) { return array(); } if (!$db_results) { return array(); }
$row = Dba::fetch_assoc($db_results); $row = Dba::fetch_assoc($db_results);
self::add_to_cache($table_name,$id,$row); self::add_to_cache($table_name,$id,$row);
return $row; return $row;
} // get_info } // get_info
@ -64,12 +64,12 @@ abstract class database_object {
* is_cached * is_cached
* this checks the cache to see if the specified object is there * this checks the cache to see if the specified object is there
*/ */
public static function is_cached($index,$id) { public static function is_cached($index,$id) {
// Make sure we've got some parents here before we dive below // Make sure we've got some parents here before we dive below
if (!isset(self::$object_cache[$index])) { return false; } if (!isset(self::$object_cache[$index])) { return false; }
return isset(self::$object_cache[$index][$id]); return isset(self::$object_cache[$index][$id]);
} // is_cached } // is_cached
@ -77,18 +77,18 @@ abstract class database_object {
* get_from_cache * get_from_cache
* This attempts to retrive the specified object from the cache we've got here * This attempts to retrive the specified object from the cache we've got here
*/ */
public static function get_from_cache($index,$id) { public static function get_from_cache($index,$id) {
// Check if the object is set // Check if the object is set
if (isset(self::$object_cache[$index]) if (isset(self::$object_cache[$index])
&& isset(self::$object_cache[$index][$id]) && isset(self::$object_cache[$index][$id])
) { ) {
self::$cache_hit++;
return self::$object_cache[$index][$id];
}
return false; self::$cache_hit++;
return self::$object_cache[$index][$id];
}
return false;
} // get_from_cache } // get_from_cache
@ -96,11 +96,11 @@ abstract class database_object {
* add_to_cache * add_to_cache
* This adds the specified object to the specified index in the cache * This adds the specified object to the specified index in the cache
*/ */
public static function add_to_cache($index,$id,$data) { public static function add_to_cache($index,$id,$data) {
if (!self::$_enabled) { return false; } if (!self::$_enabled) { return false; }
$value = is_null($data) ? false : $data; $value = is_null($data) ? false : $data;
self::$object_cache[$index][$id] = $value; self::$object_cache[$index][$id] = $value;
} // add_to_cache } // add_to_cache
@ -110,11 +110,11 @@ abstract class database_object {
* This function clears something from the cache, there are a few places we need to do this * This function clears something from the cache, there are a few places we need to do this
* in order to have things display correctly * in order to have things display correctly
*/ */
public static function remove_from_cache($index,$id) { public static function remove_from_cache($index,$id) {
if (isset(self::$object_cache[$index]) && isset(self::$object_cache[$index][$id])) { if (isset(self::$object_cache[$index]) && isset(self::$object_cache[$index][$id])) {
unset(self::$object_cache[$index][$id]); unset(self::$object_cache[$index][$id]);
} }
} // remove_from_cache } // remove_from_cache

View file

@ -1,21 +1,21 @@
<?php <?php
/* /*
Copyright (c) Ampache.org Copyright (c) Ampache.org
All rights reserved. All rights reserved.
This program is free software; you can redistribute it and/or This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License v2 modify it under the terms of the GNU General Public License v2
as published by the Free Software Foundation. as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful, This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/ */
/* Make sure they aren't directly accessing it */ /* Make sure they aren't directly accessing it */
@ -28,21 +28,21 @@ if (INIT_LOADED != '1') { exit; }
* with a few exceptions, the row and assoc will always * with a few exceptions, the row and assoc will always
* return an array, simplifying checking on the far end * return an array, simplifying checking on the far end
* it will also auto-connect as needed, and has a default * it will also auto-connect as needed, and has a default
* database simplifying queries in most cases. * database simplifying queries in most cases.
*/ */
class Dba { class Dba {
public static $stats = array('query'=>0); public static $stats = array('query'=>0);
private static $_default_db; private static $_default_db;
private static $_sql; private static $_sql;
private static $config; private static $config;
/** /**
* constructor * constructor
* This does nothing with the DBA class * This does nothing with the DBA class
*/ */
private function __construct() { private function __construct() {
// Rien a faire // Rien a faire
@ -53,34 +53,34 @@ class Dba {
* This is the meat of the class this does a query, it emulates * This is the meat of the class this does a query, it emulates
* The mysql_query function * The mysql_query function
*/ */
public static function query($sql) { public static function query($sql) {
// Run the query // Run the query
$resource = mysql_query($sql,self::dbh()); $resource = mysql_query($sql,self::dbh());
debug_event('Query',$sql,'6'); debug_event('Query',$sql,'6');
// Save the query, to make debug easier // Save the query, to make debug easier
self::$_sql = $sql; self::$_sql = $sql;
self::$stats['query']++; self::$stats['query']++;
// Do a little error checking here and try to recover from some forms of failure // Do a little error checking here and try to recover from some forms of failure
if (!$resource) { if (!$resource) {
switch (mysql_errno(self::dbh())) { switch (mysql_errno(self::dbh())) {
case '2006': case '2006':
case '2013': case '2013':
case '2055': case '2055':
debug_event('DBH','Lost connection to database server, trying to re-connect and hope nobody noticed','1'); debug_event('DBH','Lost connection to database server, trying to re-connect and hope nobody noticed','1');
self::disconnect(); self::disconnect();
// Try again // Try again
$resource = mysql_query($sql,self::dbh()); $resource = mysql_query($sql,self::dbh());
break; break;
default: default:
debug_event('DBH',mysql_error(self::dbh()) . ' ['. mysql_errno(self::dbh()) . ']','1'); debug_event('DBH',mysql_error(self::dbh()) . ' ['. mysql_errno(self::dbh()) . ']','1');
break; break;
} // end switch on error # } // end switch on error #
} // if failed query } // if failed query
return $resource; return $resource;
} // query } // query
@ -89,33 +89,33 @@ class Dba {
* This is a wrapper for query, it's so that in the future if we ever wanted * This is a wrapper for query, it's so that in the future if we ever wanted
* to split reads and writes we could * to split reads and writes we could
*/ */
public static function read($sql) { public static function read($sql) {
return self::query($sql); return self::query($sql);
} // read } // read
/** /**
* write * write
* This is a wrapper for a write query, it is so that we can split out reads and * This is a wrapper for a write query, it is so that we can split out reads and
* writes if we want to * writes if we want to
*/ */
public static function write($sql) { public static function write($sql) {
return self::query($sql); return self::query($sql);
} // write } // write
/** /**
* escape * escape
* This runs a escape on a variable so that it can be safely inserted * This runs a escape on a variable so that it can be safely inserted
* into the sql * into the sql
*/ */
public static function escape($var) { public static function escape($var) {
$string = mysql_real_escape_string($var,self::dbh()); $string = mysql_real_escape_string($var,self::dbh());
return $string; return $string;
} // escape } // escape
@ -124,13 +124,13 @@ class Dba {
* This emulates the mysql_fetch_assoc and takes a resource result * This emulates the mysql_fetch_assoc and takes a resource result
* we force it to always return an array, albit an empty one * we force it to always return an array, albit an empty one
*/ */
public static function fetch_assoc($resource) { public static function fetch_assoc($resource) {
$result = mysql_fetch_assoc($resource); $result = mysql_fetch_assoc($resource);
if (!$result) { if (!$result) {
return array(); return array();
} }
return $result; return $result;
@ -141,15 +141,15 @@ class Dba {
* This emulates the mysql_fetch_row and takes a resource result * This emulates the mysql_fetch_row and takes a resource result
* we force it to always return an array, albit an empty one * we force it to always return an array, albit an empty one
*/ */
public static function fetch_row($resource) { public static function fetch_row($resource) {
$result = mysql_fetch_row($resource); $result = mysql_fetch_row($resource);
if (!$result) { if (!$result) {
return array(); return array();
} }
return $result; return $result;
} // fetch_row } // fetch_row
@ -159,25 +159,25 @@ class Dba {
* just a count of rows returned by our select statement, this * just a count of rows returned by our select statement, this
* doesn't work for updates or inserts * doesn't work for updates or inserts
*/ */
public static function num_rows($resource) { public static function num_rows($resource) {
$result = mysql_num_rows($resource); $result = mysql_num_rows($resource);
if (!$result) { if (!$result) {
return '0'; return '0';
} }
return $result; return $result;
} // num_rows } // num_rows
/** /**
* finish * finish
* This closes a result handle and clears the memory assoicated with it * This closes a result handle and clears the memory assoicated with it
*/ */
public static function finish($resource) { public static function finish($resource) {
// Clear the result memory // Clear the result memory
mysql_free_result($resource); mysql_free_result($resource);
} // finish } // finish
@ -185,15 +185,15 @@ class Dba {
* affected_rows * affected_rows
* This emulates the mysql_affected_rows function * This emulates the mysql_affected_rows function
*/ */
public static function affected_rows($resource) { public static function affected_rows($resource) {
$result = mysql_affected_rows($resource); $result = mysql_affected_rows($resource);
if (!$result) { if (!$result) {
return '0'; return '0';
} }
return $result; return $result;
} // affected_rows } // affected_rows
@ -201,40 +201,40 @@ class Dba {
* _connect * _connect
* This connects to the database, used by the DBH function * This connects to the database, used by the DBH function
*/ */
private static function _connect($db_name) { private static function _connect($db_name) {
if (self::$_default_db == $db_name) { if (self::$_default_db == $db_name) {
$username = Config::get('database_username'); $username = Config::get('database_username');
$hostname = Config::get('database_hostname'); $hostname = Config::get('database_hostname');
$password = Config::get('database_password'); $password = Config::get('database_password');
$database = Config::get('database_name'); $database = Config::get('database_name');
} }
else { else {
// Do this later // Do this later
} }
$dbh = mysql_connect($hostname,$username,$password); $dbh = mysql_connect($hostname,$username,$password);
if (!$dbh) { debug_event('Database','Error unable to connect to database' . mysql_error(),'1'); } if (!$dbh) { debug_event('Database','Error unable to connect to database' . mysql_error(),'1'); }
$data = self::translate_to_mysqlcharset(Config::get('site_charset')); $data = self::translate_to_mysqlcharset(Config::get('site_charset'));
if (function_exists('mysql_set_charset')) { if (function_exists('mysql_set_charset')) {
if (!$charset = mysql_set_charset($data['charset'],$dbh)) { if (!$charset = mysql_set_charset($data['charset'],$dbh)) {
debug_event('Database','Error unable to set MySQL Connection charset to ' . $data['charset'] . ' this may cause issues...','1'); debug_event('Database','Error unable to set MySQL Connection charset to ' . $data['charset'] . ' this may cause issues...','1');
} }
} }
else { else {
$sql = "SET NAMES " . mysql_real_escape_string($data['charset']); $sql = "SET NAMES " . mysql_real_escape_string($data['charset']);
$charset = mysql_query($sql,$dbh); $charset = mysql_query($sql,$dbh);
if (mysql_error($dbh)) { debug_event('Database','Error unable to set MySQL Connection charset to ' . $data['charset'] . ' using SET NAMES, you may have issues','1'); } if (mysql_error($dbh)) { debug_event('Database','Error unable to set MySQL Connection charset to ' . $data['charset'] . ' using SET NAMES, you may have issues','1'); }
} }
if (!$charset) { debug_event('Database','Error unable to set connection charset, function missing or set failed','1'); } if (!$charset) { debug_event('Database','Error unable to set connection charset, function missing or set failed','1'); }
$select_db = mysql_select_db($database,$dbh);
if (!$select_db) { debug_event('Database','Error unable to select ' . $database . ' error ' . mysql_error(),'1'); }
$select_db = mysql_select_db($database,$dbh);
if (!$select_db) { debug_event('Database','Error unable to select ' . $database . ' error ' . mysql_error(),'1'); }
if (Config::get('sql_profiling')) { if (Config::get('sql_profiling')) {
mysql_query('set profiling=1', $dbh); mysql_query('set profiling=1', $dbh);
mysql_query('set profiling_history_size=50', $dbh); mysql_query('set profiling_history_size=50', $dbh);
@ -251,13 +251,13 @@ class Dba {
public static function show_profile() { public static function show_profile() {
if (Config::get('sql_profiling')) { if (Config::get('sql_profiling')) {
print '<br/>Profiling data: <br/>'; print '<br/>Profiling data: <br/>';
$res = Dba::query('show profiles'); $res = Dba::read('show profiles');
print '<table>'; print '<table>';
while ($r = Dba::fetch_row($res)) { while ($r = Dba::fetch_row($res)) {
print '<tr><td>' . implode('</td><td>', $r) . '</td></tr>'; print '<tr><td>' . implode('</td><td>', $r) . '</td></tr>';
} }
print '</table>'; print '</table>';
} }
} // show_profile } // show_profile
@ -266,21 +266,21 @@ class Dba {
* This is called by the class to return the database handle * This is called by the class to return the database handle
* for the specified database, if none is found it connects * for the specified database, if none is found it connects
*/ */
public static function dbh($database='') { public static function dbh($database='') {
if (!$database) { $database = self::$_default_db; } if (!$database) { $database = self::$_default_db; }
// Assign the Handle name that we are going to store // Assign the Handle name that we are going to store
$handle = 'dbh_' . $database; $handle = 'dbh_' . $database;
if (!is_resource(Config::get($handle))) { if (!is_resource(Config::get($handle))) {
$dbh = self::_connect($database); $dbh = self::_connect($database);
Config::set($handle,$dbh,1); Config::set($handle,$dbh,1);
return $dbh; return $dbh;
} }
else { else {
return Config::get($handle); return Config::get($handle);
} }
} // dbh } // dbh
@ -289,19 +289,19 @@ class Dba {
* disconnect * disconnect
* This nukes the dbh connection based, this isn't used very often... * This nukes the dbh connection based, this isn't used very often...
*/ */
public static function disconnect($database='') { public static function disconnect($database='') {
if (!$database) { $database = self::$_default_db; } if (!$database) { $database = self::$_default_db; }
$handle = 'dbh_' . $database; $handle = 'dbh_' . $database;
// Try to close it correctly // Try to close it correctly
mysql_close(Config::get($handle)); mysql_close(Config::get($handle));
// Nuke it // Nuke it
Config::set($handle,false,1); Config::set($handle,false,1);
return true; return true;
} // disconnect } // disconnect
@ -310,10 +310,10 @@ class Dba {
* This emulates the mysql_insert_id function, it takes * This emulates the mysql_insert_id function, it takes
* an optional database target * an optional database target
*/ */
public static function insert_id() { public static function insert_id() {
$id = mysql_insert_id(self::dbh()); $id = mysql_insert_id(self::dbh());
return $id; return $id;
} // insert_id } // insert_id
@ -321,22 +321,22 @@ class Dba {
* error * error
* this returns the error of the db * this returns the error of the db
*/ */
public static function error() { public static function error() {
return mysql_error(); return mysql_error();
} // error } // error
/** /**
* auto_init * auto_init
* This is the auto init function it sets up the config class * This is the auto init function it sets up the config class
* and also sets the default database * and also sets the default database
*/ */
public static function _auto_init() { public static function _auto_init() {
self::$_default_db = Config::get('database_name'); self::$_default_db = Config::get('database_name');
return true; return true;
} // auto_init } // auto_init
@ -344,51 +344,51 @@ class Dba {
* translate_to_mysqlcharset * translate_to_mysqlcharset
* This translates the specified charset to a mysqlcharset, stupid ass mysql * This translates the specified charset to a mysqlcharset, stupid ass mysql
* demands that it's charset list is different! * demands that it's charset list is different!
*/ */
public static function translate_to_mysqlcharset($charset) { public static function translate_to_mysqlcharset($charset) {
// MySQL translte real charset names into fancy smancy MySQL land names // MySQL translte real charset names into fancy smancy MySQL land names
switch (strtoupper($charset)) { switch (strtoupper($charset)) {
case 'CP1250': case 'CP1250':
case 'WINDOWS-1250': case 'WINDOWS-1250':
$target_charset = 'cp1250'; $target_charset = 'cp1250';
$target_collation = 'cp1250_general_ci'; $target_collation = 'cp1250_general_ci';
break; break;
case 'ISO-8859': case 'ISO-8859':
case 'ISO-8859-2': case 'ISO-8859-2':
$target_charset = 'latin2'; $target_charset = 'latin2';
$target_collation = 'latin2_general_ci'; $target_collation = 'latin2_general_ci';
break; break;
case 'ISO-8859-1': case 'ISO-8859-1':
case 'CP1252': case 'CP1252':
case 'WINDOWS-1252': case 'WINDOWS-1252':
$target_charset = 'latin1'; $target_charset = 'latin1';
$target_collation = 'latin1_general_ci'; $target_collation = 'latin1_general_ci';
break; break;
case 'EUC-KR': case 'EUC-KR':
$target_charset = 'euckr'; $target_charset = 'euckr';
$target_collation = 'euckr_korean_ci'; $target_collation = 'euckr_korean_ci';
break; break;
case 'CP932': case 'CP932':
$target_charset = 'sjis'; $target_charset = 'sjis';
$target_collation = 'sjis_japanese_ci'; $target_collation = 'sjis_japanese_ci';
break; break;
case 'KOI8-U': case 'KOI8-U':
$target_charset = 'koi8u'; $target_charset = 'koi8u';
$target_collation = 'koi8u_general_ci'; $target_collation = 'koi8u_general_ci';
break; break;
case 'KOI8-R': case 'KOI8-R':
$target_charset = 'koi8r'; $target_charset = 'koi8r';
$target_collation = 'koi8r_general_ci'; $target_collation = 'koi8r_general_ci';
break; break;
default; default;
case 'UTF-8': case 'UTF-8':
$target_charset = 'utf8'; $target_charset = 'utf8';
$target_collation = 'utf8_unicode_ci'; $target_collation = 'utf8_unicode_ci';
break; break;
} // end mysql charset translation } // end mysql charset translation
return array('charset'=>$target_charset,'collation'=>$target_collation); return array('charset'=>$target_charset,'collation'=>$target_collation);
} // translate_to_mysqlcharset } // translate_to_mysqlcharset
@ -396,43 +396,43 @@ class Dba {
* reset_db_charset * reset_db_charset
* This cruises through the database and trys to set the charset to the current * This cruises through the database and trys to set the charset to the current
* site charset, this is an admin function that can be run by an administrator * site charset, this is an admin function that can be run by an administrator
* this can mess up data if you switch between charsets that are not overlapping * this can mess up data if you switch between charsets that are not overlapping
* a catalog verify must be re-run to correct them * a catalog verify must be re-run to correct them
*/ */
public static function reset_db_charset() { public static function reset_db_charset() {
$translated_charset = self::translate_to_mysqlcharset(Config::get('site_charset')); $translated_charset = self::translate_to_mysqlcharset(Config::get('site_charset'));
$target_charset = $translated_charset['charset']; $target_charset = $translated_charset['charset'];
$target_collation = $translated_charset['collation']; $target_collation = $translated_charset['collation'];
// Alter the charset for the entire database // Alter the charset for the entire database
$sql = "ALTER DATABASE `" . Config::get('database_name') . "` DEFAULT CHARACTER SET $target_charset COLLATE $target_collation"; $sql = "ALTER DATABASE `" . Config::get('database_name') . "` DEFAULT CHARACTER SET $target_charset COLLATE $target_collation";
$db_results = Dba::query($sql); $db_results = Dba::write($sql);
$sql = "SHOW TABLES"; $sql = "SHOW TABLES";
$db_results = Dba::query($sql); $db_results = Dba::read($sql);
// Go through the tables! // Go through the tables!
while ($row = Dba::fetch_row($db_results)) { while ($row = Dba::fetch_row($db_results)) {
$sql = "DESCRIBE `" . $row['0'] . "`"; $sql = "DESCRIBE `" . $row['0'] . "`";
$describe_results = Dba::query($sql); $describe_results = Dba::read($sql);
// Change the tables default charset and colliation // Change the tables default charset and colliation
$sql = "ALTER TABLE `" . $row['0'] . "` DEFAULT CHARACTER SET $target_charset COLLATE $target_collation"; $sql = "ALTER TABLE `" . $row['0'] . "` DEFAULT CHARACTER SET $target_charset COLLATE $target_collation";
$alter_table = Dba::query($sql); $alter_table = Dba::write($sql);
// Itterate through the columns of the table
while ($table = Dba::fetch_assoc($describe_results)) {
if (strstr($table['Type'],'varchar') OR strstr($table['Type'],'enum') OR strstr($table['Table'],'text')) {
$sql = "ALTER TABLE `" . $row['0'] . "` MODIFY `" . $table['Field'] . "` " . $table['Type'] . " CHARACTER SET " . $target_charset;
$charset_results = Dba::query($sql);
if (!$charset_results) {
debug_event('CHARSET','Unable to update the charset of ' . $table['Field'] . '.' . $table['Type'] . ' to ' . $target_charset,'3');
} // if it fails
} // if its a varchar
} // end columns
} // end tables // Itterate through the columns of the table
while ($table = Dba::fetch_assoc($describe_results)) {
if (strstr($table['Type'],'varchar') OR strstr($table['Type'],'enum') OR strstr($table['Table'],'text')) {
$sql = "ALTER TABLE `" . $row['0'] . "` MODIFY `" . $table['Field'] . "` " . $table['Type'] . " CHARACTER SET " . $target_charset;
$charset_results = Dba::write($sql);
if (!$charset_results) {
debug_event('CHARSET','Unable to update the charset of ' . $table['Field'] . '.' . $table['Type'] . ' to ' . $target_charset,'3');
} // if it fails
} // if its a varchar
} // end columns
} // end tables
} // reset_db_charset } // reset_db_charset

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -834,7 +834,7 @@ class User extends database_object {
/* Get All Preferences for the current user */ /* Get All Preferences for the current user */
$sql = "SELECT * FROM `user_preference` WHERE `user`='$user_id'"; $sql = "SELECT * FROM `user_preference` WHERE `user`='$user_id'";
$db_results = Dba::query($sql); $db_results = Dba::read($sql);
$results = array(); $results = array();
@ -871,7 +871,7 @@ class User extends database_object {
if ($user_id != '-1') { if ($user_id != '-1') {
$sql .= " WHERE catagory !='system'"; $sql .= " WHERE catagory !='system'";
} }
$db_results = Dba::query($sql); $db_results = Dba::read($sql);
while ($r = Dba::fetch_assoc($db_results)) { while ($r = Dba::fetch_assoc($db_results)) {

View file

@ -15,10 +15,10 @@
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/ */
/** /**
* Vauth * Vauth
* This class handles all of the session related stuff in Ampache * This class handles all of the session related stuff in Ampache
* it takes over for the vauth libs, and takes some stuff out of other * it takes over for the vauth libs, and takes some stuff out of other
@ -33,7 +33,7 @@ class vauth {
* Constructor * Constructor
* This should never be called * This should never be called
*/ */
private function __construct() { private function __construct() {
// Rien a faire // Rien a faire
@ -44,14 +44,14 @@ class vauth {
* This function is for opening a new session so we just verify that we have * This function is for opening a new session so we just verify that we have
* a database connection, nothing more is needed * a database connection, nothing more is needed
*/ */
public static function open($save_path,$session_name) { public static function open($save_path,$session_name) {
if (!is_resource(Dba::dbh())) { if (!is_resource(Dba::dbh())) {
debug_event('SESSION','Error no database connection session failed','1'); debug_event('SESSION','Error no database connection session failed','1');
return false; return false;
} }
return true; return true;
} // open } // open
@ -59,9 +59,9 @@ class vauth {
* close * close
* This is run on the end of a sessoin, nothing to do here for now * This is run on the end of a sessoin, nothing to do here for now
*/ */
public static function close() { public static function close() {
return true; return true;
} // close } // close
@ -69,16 +69,16 @@ class vauth {
* read * read
* This takes a key and then looks in the database and returns the value * This takes a key and then looks in the database and returns the value
*/ */
public static function read($key) { public static function read($key) {
$results = self::get_session_data($key); $results = self::get_session_data($key);
if (!is_array($results)) { if (!is_array($results)) {
debug_event('SESSION','Error unable to read session from key ' . $key . ' no data found','1'); debug_event('SESSION','Error unable to read session from key ' . $key . ' no data found','1');
return false; return false;
} }
return $results['value']; return $results['value'];
} // read } // read
@ -86,22 +86,22 @@ class vauth {
* write * write
* This saves the sessoin information into the database * This saves the sessoin information into the database
*/ */
public static function write($key,$value) { public static function write($key,$value) {
if (NO_SESSION_UPDATE == '1') { return true; } if (NO_SESSION_UPDATE == '1') { return true; }
$length = Config::get('session_length'); $length = Config::get('session_length');
$value = Dba::escape($value); $value = Dba::escape($value);
$key = Dba::escape($key); $key = Dba::escape($key);
// Check to see if remember me cookie is set, if so use remember length, otherwise use the session length // Check to see if remember me cookie is set, if so use remember length, otherwise use the session length
$expire = isset($_COOKIE[Config::get('session_name') . '_remember']) ? time() + Config::get('remember_length') : time() + Config::get('session_length'); $expire = isset($_COOKIE[Config::get('session_name') . '_remember']) ? time() + Config::get('remember_length') : time() + Config::get('session_length');
$sql = "UPDATE `session` SET `value`='$value', `expire`='$expire' WHERE `id`='$key'"; $sql = "UPDATE `session` SET `value`='$value', `expire`='$expire' WHERE `id`='$key'";
$db_results = Dba::query($sql); $db_results = Dba::read($sql);
debug_event('SESSION','Writing to ' . $key . ' with expire ' . $expire . ' ' . Dba::error(),'6'); debug_event('SESSION','Writing to ' . $key . ' with expire ' . $expire . ' ' . Dba::error(),'6');
return $db_results; return $db_results;
} // write } // write
@ -109,20 +109,20 @@ class vauth {
* destroy * destroy
* This removes the specified session from the database * This removes the specified session from the database
*/ */
public static function destroy($key) { public static function destroy($key) {
$key = Dba::escape($key); $key = Dba::escape($key);
if (!strlen($key)) { return false; } if (!strlen($key)) { return false; }
// Remove anything and EVERYTHING // Remove anything and EVERYTHING
$sql = "DELETE FROM `session` WHERE `id`='$key'"; $sql = "DELETE FROM `session` WHERE `id`='$key'";
$db_results = Dba::query($sql); $db_results = Dba::write($sql);
debug_event('SESSION','Deleting Session with key:' . $key,'6'); debug_event('SESSION','Deleting Session with key:' . $key,'6');
// Destory our cookie! // Destory our cookie!
setcookie(Config::get('session_name'),'',time() - 86400); setcookie(Config::get('session_name'),'',time() - 86400);
return true; return true;
@ -132,16 +132,16 @@ class vauth {
* gc * gc
* This function is randomly called and it cleans up the poo * This function is randomly called and it cleans up the poo
*/ */
public static function gc($maxlifetime) { public static function gc($maxlifetime) {
$sql = "DELETE FROM `session` WHERE `expire` < '" . time() . "'"; $sql = "DELETE FROM `session` WHERE `expire` < '" . time() . "'";
$db_results = Dba::write($sql); $db_results = Dba::write($sql);
$sql = "DELETE FROM `tmp_browse` USING `tmp_browse` LEFT JOIN `session` ON `session`.`id`=`tmp_browse`.`sid` " . $sql = "DELETE FROM `tmp_browse` USING `tmp_browse` LEFT JOIN `session` ON `session`.`id`=`tmp_browse`.`sid` " .
"WHERE `session`.`id` IS NULL"; "WHERE `session`.`id` IS NULL";
$db_results = Dba::write($sql); $db_results = Dba::write($sql);
return true; return true;
} // gc } // gc
@ -151,13 +151,13 @@ class vauth {
* This is the function used for the Ajax logouts, if no id is passed * This is the function used for the Ajax logouts, if no id is passed
* it tries to find one from the session * it tries to find one from the session
*/ */
public static function logout($key='') { public static function logout($key='') {
// If no key is passed try to find the session id // If no key is passed try to find the session id
$key = $key ? $key : session_id(); $key = $key ? $key : session_id();
// Nuke the cookie before all else // Nuke the cookie before all else
self::destroy($key); self::destroy($key);
// Do a quick check to see if this is an AJAX'd logout request // Do a quick check to see if this is an AJAX'd logout request
// if so use the iframe to redirect // if so use the iframe to redirect
@ -184,7 +184,7 @@ class vauth {
header ('Location: ' . Config::get('web_path') . '/login.php'); header ('Location: ' . Config::get('web_path') . '/login.php');
} }
exit; exit;
} // logout } // logout
@ -193,20 +193,20 @@ class vauth {
* This takes a key and returns the raw data from the database, nothing to * This takes a key and returns the raw data from the database, nothing to
* see here move along people * see here move along people
*/ */
public static function get_session_data($key) { public static function get_session_data($key) {
$key = Dba::escape($key); $key = Dba::escape($key);
$sql = "SELECT * FROM `session` WHERE `id`='$key' AND `expire` > '" . time() . "'"; $sql = "SELECT * FROM `session` WHERE `id`='$key' AND `expire` > '" . time() . "'";
$db_results = Dba::query($sql); $db_results = Dba::read($sql);
$results = Dba::fetch_assoc($db_results); $results = Dba::fetch_assoc($db_results);
if (!count($results)) { if (!count($results)) {
return false; return false;
} }
return $results; return $results;
} // get_session_data } // get_session_data
@ -217,21 +217,21 @@ class vauth {
* same time as a header redirect. As such on view of a login a cookie is set with * same time as a header redirect. As such on view of a login a cookie is set with
* the proper name * the proper name
*/ */
public static function create_cookie() { public static function create_cookie() {
/* Setup the cookie prefs before we throw down, this is very important */ /* Setup the cookie prefs before we throw down, this is very important */
$cookie_life = Config::get('cookie_life'); $cookie_life = Config::get('cookie_life');
$cookie_path = Config::get('cookie_path'); $cookie_path = Config::get('cookie_path');
$cookie_domain = false; $cookie_domain = false;
$cookie_secure = Config::get('cookie_secure'); $cookie_secure = Config::get('cookie_secure');
session_set_cookie_params($cookie_life,$cookie_path,$cookie_domain,$cookie_secure); session_set_cookie_params($cookie_life,$cookie_path,$cookie_domain,$cookie_secure);
session_name(Config::get('session_name')); session_name(Config::get('session_name'));
/* Start the session */ /* Start the session */
self::ungimp_ie(); self::ungimp_ie();
session_start(); session_start();
} // create_cookie, just watch out for the cookie monster } // create_cookie, just watch out for the cookie monster
@ -239,10 +239,10 @@ class vauth {
* create_remember_cookie * create_remember_cookie
* This function just creates the remember me cookie, nothing special * This function just creates the remember me cookie, nothing special
*/ */
public static function create_remember_cookie() { public static function create_remember_cookie() {
$remember_length = Config::get('remember_length'); $remember_length = Config::get('remember_length');
$session_name = Config::get('session_name'); $session_name = Config::get('session_name');
Config::set('cookie_life',$remember_length,'1'); Config::set('cookie_life',$remember_length,'1');
setcookie($session_name . '_remember',"Rappelez-vous, rappelez-vous le 27 mars",time() + $remember_length,'/'); setcookie($session_name . '_remember',"Rappelez-vous, rappelez-vous le 27 mars",time() + $remember_length,'/');
@ -252,31 +252,31 @@ class vauth {
/** /**
* session_create * session_create
* This is called when you want to create a new session * This is called when you want to create a new session
* it takes care of setting the initial cookie, and inserting the first chunk of * it takes care of setting the initial cookie, and inserting the first chunk of
* data, nifty ain't it! * data, nifty ain't it!
*/ */
public static function session_create($data) { public static function session_create($data) {
// Regenerate the session ID to prevent fixation // Regenerate the session ID to prevent fixation
switch ($data['type']) { switch ($data['type']) {
case 'xml-rpc': case 'xml-rpc':
case 'api': case 'api':
$key = md5(uniqid(rand(), true)); $key = md5(uniqid(rand(), true));
break; break;
case 'mysql': case 'mysql':
default: default:
session_regenerate_id(); session_regenerate_id();
// Before refresh we don't have the cookie so we have to use session ID // Before refresh we don't have the cookie so we have to use session ID
$key = session_id(); $key = session_id();
break; break;
} // end switch on data type } // end switch on data type
$username = Dba::escape($data['username']); $username = Dba::escape($data['username']);
$ip = $_SERVER['REMOTE_ADDR'] ? Dba::escape(inet_pton($_SERVER['REMOTE_ADDR'])) : '0'; $ip = $_SERVER['REMOTE_ADDR'] ? Dba::escape(inet_pton($_SERVER['REMOTE_ADDR'])) : '0';
$type = Dba::escape($data['type']); $type = Dba::escape($data['type']);
$value = Dba::escape($data['value']); $value = Dba::escape($data['value']);
$agent = Dba::escape(substr($_SERVER['HTTP_USER_AGENT'],0,254)); $agent = Dba::escape(substr($_SERVER['HTTP_USER_AGENT'],0,254));
$expire = Dba::escape(time() + Config::get('session_length')); $expire = Dba::escape(time() + Config::get('session_length'));
/* We can't have null things here people */ /* We can't have null things here people */
@ -285,14 +285,14 @@ class vauth {
/* Insert the row */ /* Insert the row */
$sql = "INSERT INTO `session` (`id`,`username`,`ip`,`type`,`agent`,`value`,`expire`) " . $sql = "INSERT INTO `session` (`id`,`username`,`ip`,`type`,`agent`,`value`,`expire`) " .
" VALUES ('$key','$username','$ip','$type','$agent','$value','$expire')"; " VALUES ('$key','$username','$ip','$type','$agent','$value','$expire')";
$db_results = Dba::query($sql); $db_results = Dba::write($sql);
if (!$db_results) { if (!$db_results) {
debug_event('SESSION',"Session Creation Failed with Query: $sql and " . Dba::error(),'1'); debug_event('SESSION',"Session Creation Failed with Query: $sql and " . Dba::error(),'1');
return false; return false;
} }
debug_event('SESSION','Session Created:' . $key,'6'); debug_event('SESSION','Session Created:' . $key,'6');
return $key; return $key;
@ -303,33 +303,33 @@ class vauth {
* This checks for an existing sessoin and if it's still valid then go ahead and start it and return * This checks for an existing sessoin and if it's still valid then go ahead and start it and return
* true * true
*/ */
public static function check_session() { public static function check_session() {
$session_name = Config::get('session_name'); $session_name = Config::get('session_name');
// No cookie n go! // No cookie n go!
if (!isset($_COOKIE[$session_name])) { return false; } if (!isset($_COOKIE[$session_name])) { return false; }
// Check for a remember me // Check for a remember me
if (isset($_COOKIE[$session_name . '_remember'])) { if (isset($_COOKIE[$session_name . '_remember'])) {
self::create_remember_cookie(); self::create_remember_cookie();
} }
// Setup the cookie params before we start the session this is vital // Setup the cookie params before we start the session this is vital
session_set_cookie_params( session_set_cookie_params(
Config::get('cookie_life'), Config::get('cookie_life'),
Config::get('cookie_path'), Config::get('cookie_path'),
Config::get('cookie_domain'), Config::get('cookie_domain'),
Config::get('cookie_secure')); Config::get('cookie_secure'));
// Set name // Set name
session_name($session_name); session_name($session_name);
// Ungimp IE and go // Ungimp IE and go
self::ungimp_ie(); self::ungimp_ie();
session_start(); session_start();
return true; return true;
} // check_session } // check_session
@ -339,51 +339,51 @@ class vauth {
* exists, it also provides an array of key'd data that may be required * exists, it also provides an array of key'd data that may be required
* based on the type * based on the type
*/ */
public static function session_exists($type,$key,$data=array()) { public static function session_exists($type,$key,$data=array()) {
// Switch on the type they pass // Switch on the type they pass
switch ($type) { switch ($type) {
case 'xml-rpc': case 'xml-rpc':
case 'api': case 'api':
$key = Dba::escape($key); $key = Dba::escape($key);
$time = time(); $time = time();
$sql = "SELECT * FROM `session` WHERE `id`='$key' AND `expire` > '$time' AND `type`='$type'"; $sql = "SELECT * FROM `session` WHERE `id`='$key' AND `expire` > '$time' AND `type`='$type'";
$db_results = Dba::read($sql); $db_results = Dba::read($sql);
if (Dba::num_rows($db_results)) { if (Dba::num_rows($db_results)) {
return true; return true;
} }
break; break;
//FIXME: This should use the IN() mojo and compare against enabled auths //FIXME: This should use the IN() mojo and compare against enabled auths
case 'interface': case 'interface':
$key = Dba::escape($key); $key = Dba::escape($key);
$time = time(); $time = time();
$sql = "SELECT * FROM `session` WHERE `id`='$key' AND `expire` > '$time' AND `type`!='api' AND `type`!='xml-rpc'"; $sql = "SELECT * FROM `session` WHERE `id`='$key' AND `expire` > '$time' AND `type`!='api' AND `type`!='xml-rpc'";
$db_results = Dba::read($sql); $db_results = Dba::read($sql);
if (Dba::num_rows($db_results)) { if (Dba::num_rows($db_results)) {
return true; return true;
} }
break; break;
case 'stream': case 'stream':
$key = Dba::escape($key); $key = Dba::escape($key);
$ip = Dba::escape(inet_pton($data['ip'])); $ip = Dba::escape(inet_pton($data['ip']));
$agent = Dba::escape($data['agent']); $agent = Dba::escape($data['agent']);
$sql = "SELECT * FROM `session_stream` WHERE `id`='$key' AND `expire` > '$time' AND `ip`='$ip' AND `agent`='$agent'"; $sql = "SELECT * FROM `session_stream` WHERE `id`='$key' AND `expire` > '$time' AND `ip`='$ip' AND `agent`='$agent'";
$db_results = Dba::query($sql); $db_results = Dba::read($sql);
if (Dba::num_rows($db_results)) { if (Dba::num_rows($db_results)) {
return true; return true;
} }
break; break;
default: default:
return false; return false;
break; break;
} // type } // type
// Default to false // Default to false
return false; return false;
} // session_exists } // session_exists
@ -392,17 +392,17 @@ class vauth {
* This should really be extend_session but hey you gotta go with the flow * This should really be extend_session but hey you gotta go with the flow
* this takes a SID and extends it's expire * this takes a SID and extends it's expire
*/ */
public static function session_extend($sid) { public static function session_extend($sid) {
$sid = Dba::escape($sid); $sid = Dba::escape($sid);
$expire = isset($_COOKIE[Config::get('session_name') . '_remember']) ? time() + Config::get('remember_length') : time() + Config::get('session_length'); $expire = isset($_COOKIE[Config::get('session_name') . '_remember']) ? time() + Config::get('remember_length') : time() + Config::get('session_length');
$sql = "UPDATE `session` SET `expire`='$expire' WHERE `id`='$sid'"; $sql = "UPDATE `session` SET `expire`='$expire' WHERE `id`='$sid'";
$db_results = Dba::query($sql); $db_results = Dba::write($sql);
debug_event('SESSION','Session:' . $sid . ' Has been Extended to ' . $expire,'6'); debug_event('SESSION','Session:' . $sid . ' Has been Extended to ' . $expire,'6');
return $db_results; return $db_results;
} // session_extend } // session_extend
@ -410,14 +410,14 @@ class vauth {
* _auto_init * _auto_init
* This function is called when the object is included, this sets up the session_save_handler * This function is called when the object is included, this sets up the session_save_handler
*/ */
public static function _auto_init() { public static function _auto_init() {
if (!function_exists('session_start')) { if (!function_exists('session_start')) {
header("Location:" . Config::get('web_path') . "/test.php"); header("Location:" . Config::get('web_path') . "/test.php");
exit; exit;
} }
session_set_save_handler(array('vauth','open'),array('vauth','close'),array('vauth','read'),array('vauth','write'),array('vauth','destroy'),array('vauth','gc')); session_set_save_handler(array('vauth','open'),array('vauth','close'),array('vauth','read'),array('vauth','write'),array('vauth','destroy'),array('vauth','gc'));
} // auto init } // auto init
@ -427,19 +427,19 @@ class vauth {
* some flavor of IE. The detection used here is very conservative so feel free * some flavor of IE. The detection used here is very conservative so feel free
* to fix it. This only has to be done if we're rolling HTTPS * to fix it. This only has to be done if we're rolling HTTPS
*/ */
public static function ungimp_ie() { public static function ungimp_ie() {
// If no https, no ungimpage required // If no https, no ungimpage required
if ($_SERVER['HTTPS'] != 'on') { return true; } if ($_SERVER['HTTPS'] != 'on') { return true; }
// Try to detect IE // Try to detect IE
$agent = trim($_SERVER['HTTP_USER_AGENT']); $agent = trim($_SERVER['HTTP_USER_AGENT']);
if (strstr($agent,'MSIE') || strstr($agent,'Internet Explorer/')) { if (strstr($agent,'MSIE') || strstr($agent,'Internet Explorer/')) {
session_cache_limiter('public'); session_cache_limiter('public');
} }
return true; return true;
} // ungimp_ie } // ungimp_ie
@ -448,24 +448,24 @@ class vauth {
* This takes a username and password and then returns true or false * This takes a username and password and then returns true or false
* based on what happens when we try to do the auth then * based on what happens when we try to do the auth then
*/ */
public static function authenticate($username,$password) { public static function authenticate($username,$password) {
// Foreach the auth methods // Foreach the auth methods
foreach (Config::get('auth_methods') as $method) { foreach (Config::get('auth_methods') as $method) {
// Build the function name and call the custom method on this class // Build the function name and call the custom method on this class
$function_name = $method . '_auth'; $function_name = $method . '_auth';
if (!method_exists('vauth',$function_name)) { continue; }
$results = self::$function_name($username,$password); if (!method_exists('vauth',$function_name)) { continue; }
$results = self::$function_name($username,$password);
// If we achive victory return // If we achive victory return
if ($results['success']) { break; } if ($results['success']) { break; }
} // end foreach } // end foreach
return $results; return $results;
} // authenticate } // authenticate
@ -475,39 +475,39 @@ class vauth {
* and then tries to figure out if it can use the new SHA password hash or if it needs to fall * and then tries to figure out if it can use the new SHA password hash or if it needs to fall
* back on the mysql method * back on the mysql method
*/ */
private static function mysql_auth($username,$password) { private static function mysql_auth($username,$password) {
$username = Dba::escape($username); $username = Dba::escape($username);
$password = Dba::escape($password); $password = Dba::escape($password);
if (!strlen($password) OR !strlen($username)) { if (!strlen($password) OR !strlen($username)) {
Error::add('general',_('Error Username or Password incorrect, please try again')); Error::add('general',_('Error Username or Password incorrect, please try again'));
return false; return false;
} }
// We have to pull the password in order to figure out how to handle it *cry* // We have to pull the password in order to figure out how to handle it *cry*
$sql = "SELECT `password` FROM `user` WHERE `username`='$username'"; $sql = "SELECT `password` FROM `user` WHERE `username`='$username'";
$db_results = Dba::read($sql); $db_results = Dba::read($sql);
$row = Dba::fetch_assoc($db_results); $row = Dba::fetch_assoc($db_results);
// If it's using the old method then roll with that // If it's using the old method then roll with that
if (substr($row['password'],0,1) == '*' OR strlen($row['password']) < 32) { if (substr($row['password'],0,1) == '*' OR strlen($row['password']) < 32) {
$response = self::vieux_mysql_auth($username,$password); $response = self::vieux_mysql_auth($username,$password);
return $response; return $response;
} }
// Use SHA2 now... cooking with fire, SHA3 in 2012 *excitement* // Use SHA2 now... cooking with fire, SHA3 in 2012 *excitement*
$password = hash('sha256',$password); $password = hash('sha256',$password);
$sql = "SELECT `username`,`id` FROM `user` WHERE `password`='$password' AND `username`='$username'";
$db_results = Dba::read($sql);
$row = Dba::fetch_assoc($db_results); $sql = "SELECT `username`,`id` FROM `user` WHERE `password`='$password' AND `username`='$username'";
$db_results = Dba::read($sql);
if (!count($row)) { $row = Dba::fetch_assoc($db_results);
Error::add('general',_('Error Username or Password incorrect, please try again'));
return false; if (!count($row)) {
} Error::add('general',_('Error Username or Password incorrect, please try again'));
return false;
}
$row['type'] = 'mysql'; $row['type'] = 'mysql';
$row['success'] = true; $row['success'] = true;
@ -520,17 +520,17 @@ class vauth {
* vieux_mysql_auth * vieux_mysql_auth
* This is a private function, it should only be called by authenticate * This is a private function, it should only be called by authenticate
*/ */
private static function vieux_mysql_auth($username,$password) { private static function vieux_mysql_auth($username,$password) {
$password_check_sql = "PASSWORD('$password')"; $password_check_sql = "PASSWORD('$password')";
// This has to still be here because lots of people use old_password in their config file // This has to still be here because lots of people use old_password in their config file
$sql = "SELECT `password` FROM `user` WHERE `username`='$username'"; $sql = "SELECT `password` FROM `user` WHERE `username`='$username'";
$db_results = Dba::query($sql); $db_results = Dba::read($sql);
$row = Dba::fetch_assoc($db_results); $row = Dba::fetch_assoc($db_results);
$sql = "SELECT version()"; $sql = "SELECT version()";
$db_results = Dba::query($sql); $db_results = Dba::read($sql);
$version = Dba::fetch_row($db_results); $version = Dba::fetch_row($db_results);
$mysql_version = substr(preg_replace("/(\d+)\.(\d+)\.(\d+).*/","$1$2$3",$version[0]),0,3); $mysql_version = substr(preg_replace("/(\d+)\.(\d+)\.(\d+).*/","$1$2$3",$version[0]),0,3);
@ -539,7 +539,7 @@ class vauth {
} }
$sql = "SELECT `username`,`id` FROM `user` WHERE `username`='$username' AND `password`=$password_check_sql"; $sql = "SELECT `username`,`id` FROM `user` WHERE `username`='$username' AND `password`=$password_check_sql";
$db_results = Dba::query($sql); $db_results = Dba::read($sql);
$results = Dba::fetch_assoc($db_results); $results = Dba::fetch_assoc($db_results);
@ -552,14 +552,14 @@ class vauth {
$client = new User($results['id']); $client = new User($results['id']);
$current_ip = $client->is_logged_in(); $current_ip = $client->is_logged_in();
if ($current_ip AND $current_ip != inet_pton($_SERVER['REMOTE_ADDR'])) { if ($current_ip AND $current_ip != inet_pton($_SERVER['REMOTE_ADDR'])) {
debug_event('Login','Concurrent Login Failure, attempted to login from ' . $_SERVER['REMOTE_ADDR'] . ' and already logged in','1'); debug_event('Login','Concurrent Login Failure, attempted to login from ' . $_SERVER['REMOTE_ADDR'] . ' and already logged in','1');
Error::add('general','User Already Logged in'); Error::add('general','User Already Logged in');
return false; return false;
} }
} // if prevent_multiple_logins } // if prevent_multiple_logins
$results['type'] = 'mysql'; $results['type'] = 'mysql';
$results['password'] = 'old'; $results['password'] = 'old';
$results['success'] = true; $results['success'] = true;
return $results; return $results;
@ -568,7 +568,7 @@ class vauth {
/** /**
* ldap_auth * ldap_auth
* Step one, connect to the LDAP server and perform a search for teh username provided. * Step one, connect to the LDAP server and perform a search for teh username provided.
* If its found, attempt to bind using that username and the password provided. * If its found, attempt to bind using that username and the password provided.
* Step two, figure out if they are authorized to use ampache: * Step two, figure out if they are authorized to use ampache:
* TODO: need implimented still: * TODO: need implimented still:
@ -576,7 +576,7 @@ class vauth {
* * require-dn "Grant access if the DN in the directive matches the DN fetched from the LDAP directory" * * require-dn "Grant access if the DN in the directive matches the DN fetched from the LDAP directory"
* * require-attribute "an attribute fetched from the LDAP directory matches the given value" * * require-attribute "an attribute fetched from the LDAP directory matches the given value"
*/ */
private static function ldap_auth($username,$password) { private static function ldap_auth($username,$password) {
$ldap_username = Config::get('ldap_username'); $ldap_username = Config::get('ldap_username');
$ldap_password = Config::get('ldap_password'); $ldap_password = Config::get('ldap_password');
@ -632,14 +632,14 @@ class vauth {
} // if we get something good back } // if we get something good back
} // if something was sent back } // if something was sent back
} // if failed connect } // if failed connect
/* Default to bad news */ /* Default to bad news */
$results['success'] = false; $results['success'] = false;
$results['error'] = "LDAP login attempt failed"; $results['error'] = "LDAP login attempt failed";
return $results; return $results;
} // ldap_auth } // ldap_auth
@ -650,7 +650,7 @@ class vauth {
* This is not a very secure method of authentication * This is not a very secure method of authentication
* and defaults to off. * and defaults to off.
*/ */
public static function http_auth($username) { public static function http_auth($username) {
$results['success'] = true; $results['success'] = true;
$results['type'] = 'http'; $results['type'] = 'http';

View file

@ -21,9 +21,9 @@
/** /**
* xmlRpcServer * xmlRpcServer
* This class contains all the methods that the /server/xmlrpc.server.php will respond to * This class contains all the methods that the /server/xmlrpc.server.php will respond to
* to add a new method, just define a new public static function in here and it will be automagicaly * to add a new method, just define a new public static function in here and it will be automagicaly
* populated to xmlrpcserver.<FUNCTION> in /server/xmlrpc.server.php * populated to xmlrpcserver.<FUNCTION> in /server/xmlrpc.server.php
*/ */
class xmlRpcServer { class xmlRpcServer {
@ -34,53 +34,53 @@ class xmlRpcServer {
* It requires a key be passed as the first element * It requires a key be passed as the first element
* //FIXME: USE TOKEN! * //FIXME: USE TOKEN!
*/ */
public static function get_catalogs($xmlrpc_object) { public static function get_catalogs($xmlrpc_object) {
// Pull out the key // Pull out the key
$variable = $xmlrpc_object->getParam(0); $variable = $xmlrpc_object->getParam(0);
$key = $variable->scalarval(); $key = $variable->scalarval();
// Check it and make sure we're super green // Check it and make sure we're super green
if (!vauth::session_exists('xml-rpc',$key)) { if (!vauth::session_exists('xml-rpc',$key)) {
debug_event('XMLSERVER','Error ' . $_SERVER['REMOTE_ADDR'] . ' with key ' . $key . ' does not match any ACLs','1'); debug_event('XMLSERVER','Error ' . $_SERVER['REMOTE_ADDR'] . ' with key ' . $key . ' does not match any ACLs','1');
return new XML_RPC_Response(0,'503','Key/IP Mis-match Access Denied'); return new XML_RPC_Response(0,'503','Key/IP Mis-match Access Denied');
} }
// Go ahead and gather up the information they are legit // Go ahead and gather up the information they are legit
$results = array(); $results = array();
$sql = "SELECT `catalog`.`name`,COUNT(`song`.`id`) AS `count`,`catalog`.`id` AS `catalog_id` FROM `catalog` ". $sql = "SELECT `catalog`.`name`,COUNT(`song`.`id`) AS `count`,`catalog`.`id` AS `catalog_id` FROM `catalog` ".
"LEFT JOIN `song` ON `catalog`.`id`=`song`.`catalog` WHERE `catalog`.`catalog_type`='local' " . "LEFT JOIN `song` ON `catalog`.`id`=`song`.`catalog` WHERE `catalog`.`catalog_type`='local' " .
"GROUP BY `catalog`.`id`"; "GROUP BY `catalog`.`id`";
$db_results = Dba::query($sql); $db_results = Dba::read($sql);
while ($row = Dba::fetch_assoc($db_results)) { while ($row = Dba::fetch_assoc($db_results)) {
$results[] = $row; $results[] = $row;
} }
// We need to set time limit at this point as who know how long this data is going to take // We need to set time limit at this point as who know how long this data is going to take
// to return to the client // to return to the client
set_time_limit(0); set_time_limit(0);
$encoded_array = XML_RPC_encode($results); $encoded_array = XML_RPC_encode($results);
debug_event('XMLSERVER','Returning data about ' . count($results) . ' catalogs to ' . $_SERVER['REMOTE_ADDR'],'5'); debug_event('XMLSERVER','Returning data about ' . count($results) . ' catalogs to ' . $_SERVER['REMOTE_ADDR'],'5');
return new XML_RPC_Response($encoded_array); return new XML_RPC_Response($encoded_array);
} // get_catalogs } // get_catalogs
/** /**
* get_songs * get_songs
* This is a basic function to return all of the song data in a serialized format. It takes a start and end point * This is a basic function to return all of the song data in a serialized format. It takes a start and end point
* as well as the TOKEN for auth mojo * as well as the TOKEN for auth mojo
* //FIXME: USE TOKEN! * //FIXME: USE TOKEN!
*/ */
public static function get_songs($xmlrpc_object) { public static function get_songs($xmlrpc_object) {
// We're going to be here a while // We're going to be here a while
set_time_limit(0); set_time_limit(0);
// Pull out the key // Pull out the key
$variable = $xmlrpc_object->getParam(0); $variable = $xmlrpc_object->getParam(0);
$key = $variable->scalarval(); $key = $variable->scalarval();
@ -90,50 +90,50 @@ class xmlRpcServer {
debug_event('XMLSERVER','Error ' . $_SERVER['REMOTE_ADDR'] . ' with key ' . $key . ' does not match any ACLs','1'); debug_event('XMLSERVER','Error ' . $_SERVER['REMOTE_ADDR'] . ' with key ' . $key . ' does not match any ACLs','1');
return new XML_RPC_Response(0,'503','Key/IP Mis-match Access Denied'); return new XML_RPC_Response(0,'503','Key/IP Mis-match Access Denied');
} }
// Now pull out the start and end // Now pull out the start and end
$start = intval($xmlrpc_object->params['1']->me['int']); $start = intval($xmlrpc_object->params['1']->me['int']);
$end = intval($xmlrpc_object->params['2']->me['int']); $end = intval($xmlrpc_object->params['2']->me['int']);
// Get Catalogs first // Get Catalogs first
$sql = "SELECT `catalog`.`id` FROM `catalog` WHERE `catalog`.`catalog_type`='local'"; $sql = "SELECT `catalog`.`id` FROM `catalog` WHERE `catalog`.`catalog_type`='local'";
$db_results = Dba::query($sql); $db_results = Dba::read($sql);
while ($row = Dba::fetch_assoc($db_results)) { while ($row = Dba::fetch_assoc($db_results)) {
$where_sql .= "`song`.`catalog`='" . $row['id'] . "' OR"; $where_sql .= "`song`.`catalog`='" . $row['id'] . "' OR";
} }
$where_sql = rtrim($where_sql,'OR'); $where_sql = rtrim($where_sql,'OR');
$sql = "SELECT `song`.`id` FROM `song` WHERE `song`.`enabled`='1' AND ($where_sql) LIMIT $start,$end"; $sql = "SELECT `song`.`id` FROM `song` WHERE `song`.`enabled`='1' AND ($where_sql) LIMIT $start,$end";
$db_results = Dba::query($sql); $db_results = Dba::read($sql);
while ($row = Dba::fetch_assoc($db_results)) { while ($row = Dba::fetch_assoc($db_results)) {
$song = new Song($row['id']); $song = new Song($row['id']);
$song->fill_ext_info(); $song->fill_ext_info();
$song->album = $song->get_album_name(); $song->album = $song->get_album_name();
$song->artist = $song->get_artist_name(); $song->artist = $song->get_artist_name();
//$song->genre = $song->get_genre_name(); // TODO: Needs to be implemented //$song->genre = $song->get_genre_name(); // TODO: Needs to be implemented
$output = serialize($song); $output = serialize($song);
$results[] = $output ; $results[] = $output ;
} // end while } // end while
$encoded_array = XML_RPC_encode($results); $encoded_array = XML_RPC_encode($results);
debug_event('XMLSERVER','Encoded ' . count($results) . ' songs (' . $start . ',' . $end . ')','5'); debug_event('XMLSERVER','Encoded ' . count($results) . ' songs (' . $start . ',' . $end . ')','5');
return new XML_RPC_Response($encoded_array); return new XML_RPC_Response($encoded_array);
} // get_songs } // get_songs
/** /**
* get_album_images * get_album_images
* Returns the images information of the albums * Returns the images information of the albums
*/ */
public static function get_album_images($xmlrpc_object) { public static function get_album_images($xmlrpc_object) {
// We're going to be here a while // We're going to be here a while
set_time_limit(0); set_time_limit(0);
// Pull out the key // Pull out the key
$variable = $xmlrpc_object->getParam(0); $variable = $xmlrpc_object->getParam(0);
$key = $variable->scalarval(); $key = $variable->scalarval();
@ -143,12 +143,12 @@ class xmlRpcServer {
debug_event('XMLSERVER','Error ' . $_SERVER['REMOTE_ADDR'] . ' with key ' . $key . ' does not match any ACLs','1'); debug_event('XMLSERVER','Error ' . $_SERVER['REMOTE_ADDR'] . ' with key ' . $key . ' does not match any ACLs','1');
return new XML_RPC_Response(0,'503','Key/IP Mis-match Access Denied'); return new XML_RPC_Response(0,'503','Key/IP Mis-match Access Denied');
} }
// Get Albums first
$sql = "SELECT `album`.`id` FROM `album` ";
$db_results = Dba::query($sql);
while ($row = Dba::fetch_assoc($db_results)) { // Get Albums first
$sql = "SELECT `album`.`id` FROM `album` ";
$db_results = Dba::read($sql);
while ($row = Dba::fetch_assoc($db_results)) {
// Load the current album // Load the current album
$album = new Album($row['id']); $album = new Album($row['id']);
$art = $album->get_db_art(); $art = $album->get_db_art();
@ -159,18 +159,18 @@ class xmlRpcServer {
$results[] = $output; $results[] = $output;
} }
} }
$encoded_array = XML_RPC_encode($results); $encoded_array = XML_RPC_encode($results);
debug_event('XMLSERVER','Encoded ' . count($results) . 'albums with art','5'); debug_event('XMLSERVER','Encoded ' . count($results) . 'albums with art','5');
return new XML_RPC_Response($encoded_array); return new XML_RPC_Response($encoded_array);
} }
/** /**
* create_stream_session * create_stream_session
* This creates a new stream session and returns the SID in question, this requires a TOKEN as generated by the handshake * This creates a new stream session and returns the SID in question, this requires a TOKEN as generated by the handshake
*/ */
public static function create_stream_session($xmlrpc_object) { public static function create_stream_session($xmlrpc_object) {
// Pull out the key // Pull out the key
$variable = $xmlrpc_object->getParam(0); $variable = $xmlrpc_object->getParam(0);
@ -182,11 +182,11 @@ class xmlRpcServer {
return new XML_RPC_Response(0,'503','Key/IP Mis-match Access Denied'); return new XML_RPC_Response(0,'503','Key/IP Mis-match Access Denied');
} }
if (!Stream::insert_session($key,'-1')) { if (!Stream::insert_session($key,'-1')) {
debug_event('XMLSERVER','Failed to create stream session','1'); debug_event('XMLSERVER','Failed to create stream session','1');
return new XML_RPC_Response(0,'503','Failed to Create Stream Session','1'); return new XML_RPC_Response(0,'503','Failed to Create Stream Session','1');
} }
return new XML_RPC_Response(XML_RPC_encode($key)); return new XML_RPC_Response(XML_RPC_encode($key));
} // create_stream_session } // create_stream_session
@ -222,43 +222,43 @@ class xmlRpcServer {
/** /**
* handshake * handshake
* This should be run before any other XMLRPC actions, it checks the KEY encoded with a timestamp then returns a valid TOKEN to be * This should be run before any other XMLRPC actions, it checks the KEY encoded with a timestamp then returns a valid TOKEN to be
* used in all further communication * used in all further communication
*/ */
public static function handshake($xmlrpc_object) { public static function handshake($xmlrpc_object) {
debug_event('XMLSERVER','handshake: ' . print_r ($xmlrpc_object, true),'5'); debug_event('XMLSERVER','handshake: ' . print_r ($xmlrpc_object, true),'5');
// Pull out the params // Pull out the params
$encoded_key = $xmlrpc_object->params['0']->me['string']; $encoded_key = $xmlrpc_object->params['0']->me['string'];
$timestamp = $xmlrpc_object->params['1']->me['int']; $timestamp = $xmlrpc_object->params['1']->me['int'];
// Check the timestamp make sure it's recent // Check the timestamp make sure it's recent
if ($timestamp < (time() - 14400)) { if ($timestamp < (time() - 14400)) {
debug_event('XMLSERVER','Handshake failure, timestamp too old','1'); debug_event('XMLSERVER','Handshake failure, timestamp too old','1');
return new XML_RPC_Response(0,'503','Handshake failure, timestamp too old'); return new XML_RPC_Response(0,'503','Handshake failure, timestamp too old');
} }
// Log the attempt // Log the attempt
debug_event('XMLSERVER','Login Attempt, IP: ' . $_SERVER['REMOTE_ADDR'] . ' Time: ' . $timestamp . ' Hash:' . $encoded_key,'1'); debug_event('XMLSERVER','Login Attempt, IP: ' . $_SERVER['REMOTE_ADDR'] . ' Time: ' . $timestamp . ' Hash:' . $encoded_key,'1');
// Convert the IP Address to an int // Convert the IP Address to an int
$ip = Dba::escape(inet_pton($_SERVER['REMOTE_ADDR'])); $ip = Dba::escape(inet_pton($_SERVER['REMOTE_ADDR']));
// Run the query and return the key's for ACLs of type RPC that would match this IP // Run the query and return the key's for ACLs of type RPC that would match this IP
$sql = "SELECT * FROM `access_list` WHERE `type`='rpc' AND `start` <= '$ip' AND `end` >= '$ip'"; $sql = "SELECT * FROM `access_list` WHERE `type`='rpc' AND `start` <= '$ip' AND `end` >= '$ip'";
$db_results = Dba::query($sql); $db_results = Dba::read($sql);
while ($row = Dba::fetch_assoc($db_results)) {
while ($row = Dba::fetch_assoc($db_results)) {
// Build our encoded passphrase // Build our encoded passphrase
$sha256pass = hash('sha256',$timestamp . hash('sha256',$row['key'])); $sha256pass = hash('sha256',$timestamp . hash('sha256',$row['key']));
if ($sha256pass == $encoded_key) { if ($sha256pass == $encoded_key) {
$data['type'] = 'xml-rpc'; $data['type'] = 'xml-rpc';
$data['username'] = 'System'; $data['username'] = 'System';
$data['value'] = 'Handshake'; $data['value'] = 'Handshake';
$token = vauth::session_create($data); $token = vauth::session_create($data);
return new XML_RPC_Response(XML_RPC_encode($token)); return new XML_RPC_Response(XML_RPC_encode($token));
} }
} // end while rows } // end while rows

View file

@ -54,7 +54,7 @@ function check_database($host,$username,$pass) {
function check_database_inserted($dbh,$db_name) { function check_database_inserted($dbh,$db_name) {
$sql = "DESCRIBE session"; $sql = "DESCRIBE session";
$db_results = Dba::query($sql); $db_results = Dba::read($sql);
if (!$db_results) { if (!$db_results) {
return false; return false;

View file

@ -29,7 +29,7 @@ function session_exists($sid,$xml_rpc=0) {
$found = true; $found = true;
$sql = "SELECT * FROM `session` WHERE `id` = '$sid'"; $sql = "SELECT * FROM `session` WHERE `id` = '$sid'";
$db_results = Dba::query($sql); $db_results = Dba::read($sql);
if (!Dba::num_rows($db_results)) { if (!Dba::num_rows($db_results)) {
$found = false; $found = false;
@ -81,7 +81,7 @@ function extend_session($sid) {
if ($_COOKIE['amp_longsess'] == '1') { $new_time = time() + 86400*364; } if ($_COOKIE['amp_longsess'] == '1') { $new_time = time() + 86400*364; }
$sql = "UPDATE `session` SET `expire`='$new_time' WHERE `id`='$sid'"; $sql = "UPDATE `session` SET `expire`='$new_time' WHERE `id`='$sid'";
$db_results = Dba::query($sql); $db_results = Dba::write($sql);
} // extend_session } // extend_session

View file

@ -25,35 +25,35 @@
* and then runs throught $_REQUEST looking for those * and then runs throught $_REQUEST looking for those
* values and updates them for this user * values and updates them for this user
*/ */
function update_preferences($pref_id=0) { function update_preferences($pref_id=0) {
$pref_user = new User($pref_id); $pref_user = new User($pref_id);
/* Get current keys */ /* Get current keys */
$sql = "SELECT `id`,`name`,`type` FROM `preference`"; $sql = "SELECT `id`,`name`,`type` FROM `preference`";
/* If it isn't the System Account's preferences */ /* If it isn't the System Account's preferences */
if ($pref_id != '-1') { $sql .= " WHERE `catagory` != 'system'"; } if ($pref_id != '-1') { $sql .= " WHERE `catagory` != 'system'"; }
$db_results = Dba::query($sql); $db_results = Dba::read($sql);
// Collect the current possible keys // Collect the current possible keys
while ($r = Dba::fetch_assoc($db_results)) { while ($r = Dba::fetch_assoc($db_results)) {
$results[] = array('id' => $r['id'], 'name' => $r['name'],'type' => $r['type']); $results[] = array('id' => $r['id'], 'name' => $r['name'],'type' => $r['type']);
} // end collecting keys } // end collecting keys
/* Foreach through possible keys and assign them */ /* Foreach through possible keys and assign them */
foreach ($results as $data) { foreach ($results as $data) {
/* Get the Value from POST/GET var called $data */ /* Get the Value from POST/GET var called $data */
$type = $data['type']; $type = $data['type'];
$name = $data['name']; $name = $data['name'];
$apply_to_all = 'check_' . $data['name']; $apply_to_all = 'check_' . $data['name'];
$new_level = 'level_' . $data['name']; $new_level = 'level_' . $data['name'];
$id = $data['id']; $id = $data['id'];
$value = scrub_in($_REQUEST[$name]); $value = scrub_in($_REQUEST[$name]);
/* Some preferences require some extra checks to be performed */ /* Some preferences require some extra checks to be performed */
switch ($name) { switch ($name) {
case 'sample_rate': case 'sample_rate':
$value = Stream::validate_bitrate($value); $value = Stream::validate_bitrate($value);
break; break;
@ -61,24 +61,24 @@ function update_preferences($pref_id=0) {
case 'librefm_pass': case 'librefm_pass':
case 'lastfm_pass': case 'lastfm_pass':
/* If it's our default blanking thing then don't use it */ /* If it's our default blanking thing then don't use it */
if ($value == '******') { unset($_REQUEST[$name]); break; } if ($value == '******') { unset($_REQUEST[$name]); break; }
$value = md5($value); $value = md5($value);
break; break;
default: default:
break; break;
} }
/* Run the update for this preference only if it's set */ /* Run the update for this preference only if it's set */
if (isset($_REQUEST[$name])) { if (isset($_REQUEST[$name])) {
Preference::update($id,$pref_id,$value,$_REQUEST[$apply_to_all]); Preference::update($id,$pref_id,$value,$_REQUEST[$apply_to_all]);
if (Access::check('interface','100') AND $_REQUEST[$new_level]) { if (Access::check('interface','100') AND $_REQUEST[$new_level]) {
Preference::update_level($id,$_REQUEST[$new_level]); Preference::update_level($id,$_REQUEST[$new_level]);
} }
} }
} // end foreach preferences } // end foreach preferences
// Now that we've done that we need to invalidate the cached preverences // Now that we've done that we need to invalidate the cached preverences
Preference::clear_from_session(); Preference::clear_from_session();
} // update_preferences } // update_preferences
@ -86,26 +86,26 @@ function update_preferences($pref_id=0) {
* update_preference * update_preference
* This function updates a single preference and is called by the update_preferences function * This function updates a single preference and is called by the update_preferences function
*/ */
function update_preference($user_id,$name,$pref_id,$value) { function update_preference($user_id,$name,$pref_id,$value) {
$apply_check = "check_" . $name; $apply_check = "check_" . $name;
$level_check = "level_" . $name; $level_check = "level_" . $name;
/* First see if they are an administrator and we are applying this to everything */ /* First see if they are an administrator and we are applying this to everything */
if ($GLOBALS['user']->has_access(100) AND make_bool($_REQUEST[$apply_check])) { if ($GLOBALS['user']->has_access(100) AND make_bool($_REQUEST[$apply_check])) {
Preference::update_all($pref_id,$value); Preference::update_all($pref_id,$value);
return true; return true;
} }
/* Check and see if they are an admin and the level def is set */ /* Check and see if they are an admin and the level def is set */
if ($GLOBALS['user']->has_access(100) AND make_bool($_REQUEST[$level_check])) { if ($GLOBALS['user']->has_access(100) AND make_bool($_REQUEST[$level_check])) {
Preference::update_level($pref_id,$_REQUEST[$level_check]); Preference::update_level($pref_id,$_REQUEST[$level_check]);
} }
/* Else make sure that the current users has the right to do this */ /* Else make sure that the current users has the right to do this */
if (Preference::has_access($name)) { if (Preference::has_access($name)) {
$sql = "UPDATE `user_preference` SET `value`='$value' WHERE `preference`='$pref_id' AND `user`='$user_id'"; $sql = "UPDATE `user_preference` SET `value`='$value' WHERE `preference`='$pref_id' AND `user`='$user_id'";
$db_results = Dba::query($sql); $db_results = Dba::write($sql);
return true; return true;
} }
@ -117,23 +117,23 @@ function update_preference($user_id,$name,$pref_id,$value) {
* create_preference_input * create_preference_input
* takes the key and then creates the correct type of input for updating it * takes the key and then creates the correct type of input for updating it
*/ */
function create_preference_input($name,$value) { function create_preference_input($name,$value) {
// Escape it for output // Escape it for output
$value = scrub_out($value); $value = scrub_out($value);
$len = strlen($value); $len = strlen($value);
if ($len <= 1) { $len = 8; } if ($len <= 1) { $len = 8; }
if (!Preference::has_access($name)) { if (!Preference::has_access($name)) {
if ($value == '1') { if ($value == '1') {
echo "Enabled"; echo "Enabled";
} }
elseif ($value == '0') { elseif ($value == '0') {
echo "Disabled"; echo "Disabled";
} }
else { else {
echo $value; echo $value;
} }
return; return;
} // if we don't have access to it } // if we don't have access to it
@ -159,7 +159,7 @@ function create_preference_input($name,$value) {
case 'rio_global_stats': case 'rio_global_stats':
case 'embed_xspf': case 'embed_xspf':
case 'direct_link': case 'direct_link':
if ($value == '1') { $is_true = "selected=\"selected\""; } if ($value == '1') { $is_true = "selected=\"selected\""; }
else { $is_false = "selected=\"selected\""; } else { $is_false = "selected=\"selected\""; }
echo "<select name=\"$name\">\n"; echo "<select name=\"$name\">\n";
echo "\t<option value=\"1\" $is_true>" . _("Enable") . "</option>\n"; echo "\t<option value=\"1\" $is_true>" . _("Enable") . "</option>\n";
@ -167,27 +167,27 @@ function create_preference_input($name,$value) {
echo "</select>\n"; echo "</select>\n";
break; break;
case 'play_type': case 'play_type':
if ($value == 'localplay') { $is_local = 'selected="selected"'; } if ($value == 'localplay') { $is_local = 'selected="selected"'; }
elseif ($value == 'democratic') { $is_vote = 'selected="selected"'; } elseif ($value == 'democratic') { $is_vote = 'selected="selected"'; }
elseif ($value == 'xspf_player') { $is_xspf_player = 'selected="selected"'; } elseif ($value == 'xspf_player') { $is_xspf_player = 'selected="selected"'; }
else { $is_stream = "selected=\"selected\""; } else { $is_stream = "selected=\"selected\""; }
echo "<select name=\"$name\">\n"; echo "<select name=\"$name\">\n";
echo "\t<option value=\"\">" . _('None') . "</option>\n"; echo "\t<option value=\"\">" . _('None') . "</option>\n";
if (Config::get('allow_stream_playback')) { if (Config::get('allow_stream_playback')) {
echo "\t<option value=\"stream\" $is_stream>" . _('Stream') . "</option>\n"; echo "\t<option value=\"stream\" $is_stream>" . _('Stream') . "</option>\n";
} }
if (Config::get('allow_democratic_playback')) { if (Config::get('allow_democratic_playback')) {
echo "\t<option value=\"democratic\" $is_vote>" . _('Democratic') . "</option>\n"; echo "\t<option value=\"democratic\" $is_vote>" . _('Democratic') . "</option>\n";
} }
if (Config::get('allow_localplay_playback')) { if (Config::get('allow_localplay_playback')) {
echo "\t<option value=\"localplay\" $is_local>" . _('Localplay') . "</option>\n"; echo "\t<option value=\"localplay\" $is_local>" . _('Localplay') . "</option>\n";
} }
echo "\t<option value=\"xspf_player\" $is_xspf_player>" . _('Flash Player') . "</option>\n"; echo "\t<option value=\"xspf_player\" $is_xspf_player>" . _('Flash Player') . "</option>\n";
echo "</select>\n"; echo "</select>\n";
break; break;
case 'playlist_type': case 'playlist_type':
$var_name = $value . "_type"; $var_name = $value . "_type";
${$var_name} = "selected=\"selected\""; ${$var_name} = "selected=\"selected\"";
echo "<select name=\"$name\">\n"; echo "<select name=\"$name\">\n";
echo "\t<option value=\"m3u\" $m3u_type>" . _('M3U') . "</option>\n"; echo "\t<option value=\"m3u\" $m3u_type>" . _('M3U') . "</option>\n";
echo "\t<option value=\"simple_m3u\" $simple_m3u_type>" . _('Simple M3U') . "</option>\n"; echo "\t<option value=\"simple_m3u\" $simple_m3u_type>" . _('Simple M3U') . "</option>\n";
@ -201,12 +201,12 @@ function create_preference_input($name,$value) {
$languages = get_languages(); $languages = get_languages();
$var_name = $value . "_lang"; $var_name = $value . "_lang";
${$var_name} = "selected=\"selected\""; ${$var_name} = "selected=\"selected\"";
echo "<select name=\"$name\">\n"; echo "<select name=\"$name\">\n";
foreach ($languages as $lang=>$name) { foreach ($languages as $lang=>$name) {
$var_name = $lang . "_lang"; $var_name = $lang . "_lang";
echo "\t<option value=\"$lang\" " . ${$var_name} . ">$name</option>\n"; echo "\t<option value=\"$lang\" " . ${$var_name} . ">$name</option>\n";
} // end foreach } // end foreach
echo "</select>\n"; echo "</select>\n";
@ -215,18 +215,18 @@ function create_preference_input($name,$value) {
$controllers = Localplay::get_controllers(); $controllers = Localplay::get_controllers();
echo "<select name=\"$name\">\n"; echo "<select name=\"$name\">\n";
echo "\t<option value=\"\">" . _('None') . "</option>\n"; echo "\t<option value=\"\">" . _('None') . "</option>\n";
foreach ($controllers as $controller) { foreach ($controllers as $controller) {
if (!Localplay::is_enabled($controller)) { continue; } if (!Localplay::is_enabled($controller)) { continue; }
$is_selected = ''; $is_selected = '';
if ($value == $controller) { $is_selected = 'selected="selected"'; } if ($value == $controller) { $is_selected = 'selected="selected"'; }
echo "\t<option value=\"" . $controller . "\" $is_selected>" . ucfirst($controller) . "</option>\n"; echo "\t<option value=\"" . $controller . "\" $is_selected>" . ucfirst($controller) . "</option>\n";
} // end foreach } // end foreach
echo "</select>\n"; echo "</select>\n";
break; break;
case 'localplay_level': case 'localplay_level':
if ($value == '25') { $is_user = 'selected="selected"'; } if ($value == '25') { $is_user = 'selected="selected"'; }
elseif ($value == '100') { $is_admin = 'selected="selected"'; } elseif ($value == '100') { $is_admin = 'selected="selected"'; }
elseif ($value == '50') { $is_manager = 'selected="selected"'; } elseif ($value == '50') { $is_manager = 'selected="selected"'; }
echo "<select name=\"$name\">\n"; echo "<select name=\"$name\">\n";
echo "<option value=\"0\">" . _('Disabled') . "</option>\n"; echo "<option value=\"0\">" . _('Disabled') . "</option>\n";
echo "<option value=\"25\" $is_user>" . _('User') . "</option>\n"; echo "<option value=\"25\" $is_user>" . _('User') . "</option>\n";
@ -237,7 +237,7 @@ function create_preference_input($name,$value) {
case 'theme_name': case 'theme_name':
$themes = get_themes(); $themes = get_themes();
echo "<select name=\"$name\">\n"; echo "<select name=\"$name\">\n";
foreach ($themes as $theme) { foreach ($themes as $theme) {
$is_selected = ""; $is_selected = "";
if ($value == $theme['path']) { $is_selected = "selected=\"selected\""; } if ($value == $theme['path']) { $is_selected = "selected=\"selected\""; }
echo "\t<option value=\"" . $theme['path'] . "\" $is_selected>" . $theme['name'] . "</option>\n"; echo "\t<option value=\"" . $theme['path'] . "\" $is_selected>" . $theme['name'] . "</option>\n";
@ -248,25 +248,25 @@ function create_preference_input($name,$value) {
case 'librefm_pass': case 'librefm_pass':
echo "<input type=\"password\" size=\"16\" name=\"$name\" value=\"******\" />"; echo "<input type=\"password\" size=\"16\" name=\"$name\" value=\"******\" />";
break; break;
case 'playlist_method': case 'playlist_method':
${$value} = ' selected="selected"'; ${$value} = ' selected="selected"';
echo "<select name=\"$name\">\n"; echo "<select name=\"$name\">\n";
echo "\t<option value=\"send\"$send>" . _('Send on Add') . "</option>\n"; echo "\t<option value=\"send\"$send>" . _('Send on Add') . "</option>\n";
echo "\t<option value=\"send_clear\"$send_clear>" . _('Send and Clear on Add') . "</option>\n"; echo "\t<option value=\"send_clear\"$send_clear>" . _('Send and Clear on Add') . "</option>\n";
echo "\t<option value=\"clear\"$clear>" . _('Clear on Send') . "</option>\n"; echo "\t<option value=\"clear\"$clear>" . _('Clear on Send') . "</option>\n";
echo "\t<option value=\"default\"$default>" . _('Default') . "</option>\n"; echo "\t<option value=\"default\"$default>" . _('Default') . "</option>\n";
echo "</select>\n"; echo "</select>\n";
break; break;
case 'transcode': case 'transcode':
${$value} = ' selected="selected"'; ${$value} = ' selected="selected"';
echo "<select name=\"$name\">\n"; echo "<select name=\"$name\">\n";
echo "\t<option value=\"never\"$never>" . _('Never') . "</option>\n"; echo "\t<option value=\"never\"$never>" . _('Never') . "</option>\n";
echo "\t<option value=\"default\"$default>" . _('Default') . "</option>\n"; echo "\t<option value=\"default\"$default>" . _('Default') . "</option>\n";
echo "\t<option value=\"always\"$always>" . _('Always') . "</option>\n"; echo "\t<option value=\"always\"$always>" . _('Always') . "</option>\n";
echo "</select>\n"; echo "</select>\n";
break; break;
case 'show_lyrics': case 'show_lyrics':
if ($value == '1') { $is_true = "selected=\"selected\""; } if ($value == '1') { $is_true = "selected=\"selected\""; }
else { $is_false = "selected=\"selected\""; } else { $is_false = "selected=\"selected\""; }
echo "<select name=\"$name\">\n"; echo "<select name=\"$name\">\n";
echo "\t<option value=\"1\" $is_true>" . _("Enable") . "</option>\n"; echo "\t<option value=\"1\" $is_true>" . _("Enable") . "</option>\n";
@ -277,7 +277,7 @@ function create_preference_input($name,$value) {
echo "<input type=\"text\" size=\"$len\" name=\"$name\" value=\"$value\" />"; echo "<input type=\"text\" size=\"$len\" name=\"$name\" value=\"$value\" />";
break; break;
} }
} // create_preference_input } // create_preference_input

View file

@ -85,10 +85,10 @@ if (!function_exists('_')) {
* ngettext * ngettext
* checks for ngettext and defines it if it doesn't exist * checks for ngettext and defines it if it doesn't exist
*/ */
if (!function_exists('ngettext')) { if (!function_exists('ngettext')) {
function ngettext($string) { function ngettext($string) {
return $string; return $string;
} }
} // if no ngettext } // if no ngettext
/** /**
@ -97,11 +97,11 @@ if (!function_exists('ngettext')) {
* that they aren't allowed to * that they aren't allowed to
*/ */
function access_denied() { function access_denied() {
// Clear any crap we've got up top // Clear any crap we've got up top
ob_end_clean(); ob_end_clean();
require_once Config::get('prefix') . '/templates/show_denied.inc.php'; require_once Config::get('prefix') . '/templates/show_denied.inc.php';
exit; exit;
} // access_denied } // access_denied
@ -119,11 +119,11 @@ function return_referer() {
} }
else { else {
$file = basename($referer); $file = basename($referer);
/* Strip off the filename */ /* Strip off the filename */
$referer = substr($referer,0,strlen($referer)-strlen($file)); $referer = substr($referer,0,strlen($referer)-strlen($file));
} }
if (substr($referer,strlen($referer)-6,6) == 'admin/') { if (substr($referer,strlen($referer)-6,6) == 'admin/') {
$file = 'admin/' . $file; $file = 'admin/' . $file;
} }
@ -141,8 +141,8 @@ function return_referer() {
*/ */
function truncate_with_ellipsis($text, $max='') { function truncate_with_ellipsis($text, $max='') {
$max = $max ? $max : '27'; $max = $max ? $max : '27';
/* If we want it to be shorter than three, just throw it back */ /* If we want it to be shorter than three, just throw it back */
if ($max > 3) { if ($max > 3) {
@ -171,9 +171,9 @@ function truncate_with_ellipsis($text, $max='') {
* This shows the header.inc.php, it may do something * This shows the header.inc.php, it may do something
* more in the future * more in the future
*/ */
function show_header() { function show_header() {
require_once Config::get('prefix') . '/templates/header.inc.php'; require_once Config::get('prefix') . '/templates/header.inc.php';
} // show_header } // show_header
@ -203,9 +203,9 @@ function img_resize($image,$size,$type,$album_id) {
return $image['raw']; return $image['raw'];
} }
// Already resized // Already resized
if ($image['db_resized']) { if ($image['db_resized']) {
debug_event('using_resized','using resized image for Album:' . $album_id,'2'); debug_event('using_resized','using resized image for Album:' . $album_id,'2');
return $image['raw']; return $image['raw'];
} }
$image = $image['raw']; $image = $image['raw'];
@ -226,11 +226,11 @@ function img_resize($image,$size,$type,$album_id) {
} }
$src = imagecreatefromstring($image); $src = imagecreatefromstring($image);
if (!$src) { if (!$src) {
debug_event('IMG_RESIZE','Failed to create from string','3'); debug_event('IMG_RESIZE','Failed to create from string','3');
return false; return false;
} }
$width = imagesx($src); $width = imagesx($src);
$height = imagesy($src); $height = imagesy($src);
@ -239,13 +239,13 @@ function img_resize($image,$size,$type,$album_id) {
$new_h = $size['height']; $new_h = $size['height'];
$img = imagecreatetruecolor($new_w,$new_h); $img = imagecreatetruecolor($new_w,$new_h);
if (!imagecopyresampled($img,$src,0,0,0,0,$new_w,$new_h,$width,$height)) { if (!imagecopyresampled($img,$src,0,0,0,0,$new_w,$new_h,$width,$height)) {
debug_event('IMG_RESIZE','Failed to copy resample image','3'); debug_event('IMG_RESIZE','Failed to copy resample image','3');
return false; return false;
} }
ob_start(); ob_start();
// determine image type and send it to the client // determine image type and send it to the client
switch ($type) { switch ($type) {
@ -262,19 +262,19 @@ function img_resize($image,$size,$type,$album_id) {
} }
// Grab this image data and save it into the thumbnail // Grab this image data and save it into the thumbnail
$data = ob_get_contents(); $data = ob_get_contents();
ob_end_clean(); ob_end_clean();
// If our image create failed don't save it, just return // If our image create failed don't save it, just return
if (!$data) { if (!$data) {
debug_event('IMG_RESIZE','Failed to resize Art from Album:' . $album_id,'3'); debug_event('IMG_RESIZE','Failed to resize Art from Album:' . $album_id,'3');
return $image; return $image;
} }
// Save what we've got // Save what we've got
Album::save_resized_art($data,'image/' . $type,$album_id); Album::save_resized_art($data,'image/' . $type,$album_id);
return $data; return $data;
} // img_resize } // img_resize
@ -293,10 +293,10 @@ function get_location() {
$location = array(); $location = array();
if (strlen($_SERVER['PHP_SELF'])) { if (strlen($_SERVER['PHP_SELF'])) {
$source = $_SERVER['PHP_SELF']; $source = $_SERVER['PHP_SELF'];
} }
else { else {
$source = $_SERVER['REQUEST_URI']; $source = $_SERVER['REQUEST_URI'];
} }
@ -388,8 +388,8 @@ function get_location() {
* it takes a chunck of the crazy preference array and then displays it out * it takes a chunck of the crazy preference array and then displays it out
* it does not contain the <form> </form> tags * it does not contain the <form> </form> tags
*/ */
function show_preference_box($preferences) { function show_preference_box($preferences) {
require Config::get('prefix') . '/templates/show_preference_box.inc.php'; require Config::get('prefix') . '/templates/show_preference_box.inc.php';
} // show_preference_box } // show_preference_box
@ -432,9 +432,9 @@ function good_email($email) {
/** /**
* show_album_select * show_album_select
* This displays a select of every album that we've got in Ampache, (it can be hella long) it's used * This displays a select of every album that we've got in Ampache, (it can be hella long) it's used
* by the Edit page, it takes a $name and a $album_id * by the Edit page, it takes a $name and a $album_id
*/ */
function show_album_select($name='album',$album_id=0,$allow_add=0,$song_id=0) { function show_album_select($name='album',$album_id=0,$allow_add=0,$song_id=0) {
// Generate key to use for HTML element ID // Generate key to use for HTML element ID
static $id_cnt; static $id_cnt;
if ($song_id) { if ($song_id) {
@ -447,17 +447,17 @@ function show_album_select($name='album',$album_id=0,$allow_add=0,$song_id=0) {
echo "<select name=\"$name\" id=\"$key\">\n"; echo "<select name=\"$name\" id=\"$key\">\n";
$sql = "SELECT `id`, `name`, `prefix` FROM `album` ORDER BY `name`"; $sql = "SELECT `id`, `name`, `prefix` FROM `album` ORDER BY `name`";
$db_results = Dba::query($sql); $db_results = Dba::read($sql);
while ($r = Dba::fetch_assoc($db_results)) { while ($r = Dba::fetch_assoc($db_results)) {
$selected = ''; $selected = '';
$album_name = trim($r['prefix'] . " " . $r['name']); $album_name = trim($r['prefix'] . " " . $r['name']);
if ($r['id'] == $album_id) { if ($r['id'] == $album_id) {
$selected = "selected=\"selected\""; $selected = "selected=\"selected\"";
} }
echo "\t<option value=\"" . $r['id'] . "\" $selected>" . scrub_out($album_name) . "</option>\n"; echo "\t<option value=\"" . $r['id'] . "\" $selected>" . scrub_out($album_name) . "</option>\n";
} // end while } // end while
if ($allow_add) { if ($allow_add) {
@ -473,7 +473,7 @@ function show_album_select($name='album',$album_id=0,$allow_add=0,$song_id=0) {
* show_artist_select * show_artist_select
* This is the same as the album select except it's *gasp* for artists how inventive! * This is the same as the album select except it's *gasp* for artists how inventive!
*/ */
function show_artist_select($name='artist', $artist_id=0, $allow_add=0, $song_id=0) { function show_artist_select($name='artist', $artist_id=0, $allow_add=0, $song_id=0) {
// Generate key to use for HTML element ID // Generate key to use for HTML element ID
static $id_cnt; static $id_cnt;
if ($song_id) { if ($song_id) {
@ -483,14 +483,14 @@ function show_artist_select($name='artist', $artist_id=0, $allow_add=0, $song_id
} }
echo "<select name=\"$name\" id=\"$key\">\n"; echo "<select name=\"$name\" id=\"$key\">\n";
$sql = "SELECT `id`, `name`, `prefix` FROM `artist` ORDER BY `name`"; $sql = "SELECT `id`, `name`, `prefix` FROM `artist` ORDER BY `name`";
$db_results = Dba::query($sql); $db_results = Dba::read($sql);
while ($r = Dba::fetch_assoc($db_results)) { while ($r = Dba::fetch_assoc($db_results)) {
$selected = ''; $selected = '';
$artist_name = trim($r['prefix'] . " " . $r['name']); $artist_name = trim($r['prefix'] . " " . $r['name']);
if ($r['id'] == $artist_id) { if ($r['id'] == $artist_id) {
$selected = "selected=\"selected\""; $selected = "selected=\"selected\"";
} }
@ -509,18 +509,18 @@ function show_artist_select($name='artist', $artist_id=0, $allow_add=0, $song_id
/** /**
* show_catalog_select * show_catalog_select
* Yet another one of these buggers. this shows a drop down of all of your catalogs * Yet another one of these buggers. this shows a drop down of all of your catalogs
*/ */
function show_catalog_select($name='catalog',$catalog_id=0,$style='') { function show_catalog_select($name='catalog',$catalog_id=0,$style='') {
echo "<select name=\"$name\" style=\"$style\">\n"; echo "<select name=\"$name\" style=\"$style\">\n";
$sql = "SELECT `id`, `name` FROM `catalog` ORDER BY `name`"; $sql = "SELECT `id`, `name` FROM `catalog` ORDER BY `name`";
$db_results = Dba::query($sql); $db_results = Dba::read($sql);
while ($r = Dba::fetch_assoc($db_results)) { while ($r = Dba::fetch_assoc($db_results)) {
$selected = ''; $selected = '';
if ($r['id'] == $catalog_id) { if ($r['id'] == $catalog_id) {
$selected = "selected=\"selected\""; $selected = "selected=\"selected\"";
} }
@ -537,21 +537,21 @@ function show_catalog_select($name='catalog',$catalog_id=0,$style='') {
* This one is for users! shows a select/option statement so you can pick a user * This one is for users! shows a select/option statement so you can pick a user
* to blame * to blame
*/ */
function show_user_select($name,$selected='',$style='') { function show_user_select($name,$selected='',$style='') {
echo "<select name=\"$name\" style=\"$style\">\n"; echo "<select name=\"$name\" style=\"$style\">\n";
echo "\t<option value=\"\">" . _('All') . "</option>\n"; echo "\t<option value=\"\">" . _('All') . "</option>\n";
$sql = "SELECT `id`,`username`,`fullname` FROM `user` ORDER BY `fullname`"; $sql = "SELECT `id`,`username`,`fullname` FROM `user` ORDER BY `fullname`";
$db_results = Dba::query($sql); $db_results = Dba::read($sql);
while ($row = Dba::fetch_assoc($db_results)) { while ($row = Dba::fetch_assoc($db_results)) {
$select_txt = ''; $select_txt = '';
if ($row['id'] == $selected) { if ($row['id'] == $selected) {
$select_txt = 'selected="selected"'; $select_txt = 'selected="selected"';
} }
// If they don't have a full name, revert to the username // If they don't have a full name, revert to the username
$row['fullname'] = $row['fullname'] ? $row['fullname'] : $row['username']; $row['fullname'] = $row['fullname'] ? $row['fullname'] : $row['username'];
echo "\t<option value=\"" . $row['id'] . "\" $select_txt>" . scrub_out($row['fullname']) . "</option>\n"; echo "\t<option value=\"" . $row['id'] . "\" $select_txt>" . scrub_out($row['fullname']) . "</option>\n";
} // end while users } // end while users
@ -565,17 +565,17 @@ function show_user_select($name,$selected='',$style='') {
* This one is for users! shows a select/option statement so you can pick a user * This one is for users! shows a select/option statement so you can pick a user
* to blame * to blame
*/ */
function show_playlist_select($name,$selected='',$style='') { function show_playlist_select($name,$selected='',$style='') {
echo "<select name=\"$name\" style=\"$style\">\n"; echo "<select name=\"$name\" style=\"$style\">\n";
echo "\t<option value=\"\">" . _('None') . "</option>\n"; echo "\t<option value=\"\">" . _('None') . "</option>\n";
$sql = "SELECT `id`,`name` FROM `playlist` ORDER BY `name`"; $sql = "SELECT `id`,`name` FROM `playlist` ORDER BY `name`";
$db_results = Dba::query($sql); $db_results = Dba::read($sql);
while ($row = Dba::fetch_assoc($db_results)) { while ($row = Dba::fetch_assoc($db_results)) {
$select_txt = ''; $select_txt = '';
if ($row['id'] == $selected) { if ($row['id'] == $selected) {
$select_txt = 'selected="selected"'; $select_txt = 'selected="selected"';
} }
// If they don't have a full name, revert to the username // If they don't have a full name, revert to the username
@ -591,9 +591,9 @@ function show_playlist_select($name,$selected='',$style='') {
* This function requires the top part of the box * This function requires the top part of the box
* it takes title as an optional argument * it takes title as an optional argument
*/ */
function show_box_top($title='',$class='') { function show_box_top($title='',$class='') {
require Config::get('prefix') . '/templates/show_box_top.inc.php'; require Config::get('prefix') . '/templates/show_box_top.inc.php';
} // show_box_top } // show_box_top
@ -602,7 +602,7 @@ function show_box_top($title='',$class='') {
* This function requires the bottom part of the box * This function requires the bottom part of the box
* it does not take any arguments * it does not take any arguments
*/ */
function show_box_bottom() { function show_box_bottom() {
require Config::get('prefix') . '/templates/show_box_bottom.inc.php'; require Config::get('prefix') . '/templates/show_box_bottom.inc.php';
@ -611,58 +611,58 @@ function show_box_bottom() {
/** /**
* get_user_icon * get_user_icon
* this function takes a name and a returns either a text representation * this function takes a name and a returns either a text representation
* or an <img /> tag * or an <img /> tag
*/ */
function get_user_icon($name,$title='',$id='') { function get_user_icon($name,$title='',$id='') {
/* Because we do a lot of calls cache the URLs */ /* Because we do a lot of calls cache the URLs */
static $url_cache = array(); static $url_cache = array();
// If our name is an array // If our name is an array
if (is_array($name)) { if (is_array($name)) {
$hover_name = $name['1']; $hover_name = $name['1'];
$name = $name['0']; $name = $name['0'];
}
if (!$title) { $title = _(ucfirst($name)); }
if ($id) {
$id_element = 'id="' . $id . '"';
}
if (isset($url_cache[$name])) {
$img_url = $url_cache[$name];
$cache_url = true;
} }
if (isset($url_cache[$hover_name])) {
if (!$title) { $title = _(ucfirst($name)); }
if ($id) {
$id_element = 'id="' . $id . '"';
}
if (isset($url_cache[$name])) {
$img_url = $url_cache[$name];
$cache_url = true;
}
if (isset($url_cache[$hover_name])) {
$hover_url = $url_cache[$hover_name]; $hover_url = $url_cache[$hover_name];
$cache_hover = true; $cache_hover = true;
} }
if (empty($hover_name)) { $cache_hover = true; }
if (!isset($cache_url) OR !isset($cache_hover)) { if (empty($hover_name)) { $cache_hover = true; }
if (!isset($cache_url) OR !isset($cache_hover)) {
$icon_name = 'icon_' . $name . '.png'; $icon_name = 'icon_' . $name . '.png';
/* Build the image url */ /* Build the image url */
if (file_exists(Config::get('prefix') . Config::get('theme_path') . '/images/icons/' . $icon_name)) { if (file_exists(Config::get('prefix') . Config::get('theme_path') . '/images/icons/' . $icon_name)) {
$img_url = Config::get('web_path') . Config::get('theme_path') . '/images/icons/' . $icon_name; $img_url = Config::get('web_path') . Config::get('theme_path') . '/images/icons/' . $icon_name;
} }
else { else {
$img_url = Config::get('web_path') . '/images/' . $icon_name; $img_url = Config::get('web_path') . '/images/' . $icon_name;
} }
/* If Hover, then build its url */ /* If Hover, then build its url */
if (!empty($hover_name)) { if (!empty($hover_name)) {
$hover_icon = 'icon_' . $hover_name . '.png'; $hover_icon = 'icon_' . $hover_name . '.png';
if (file_exists(Config::get('prefix') . Config::get('theme_path') . '/images/icons/' . $icon_name)) { if (file_exists(Config::get('prefix') . Config::get('theme_path') . '/images/icons/' . $icon_name)) {
$hov_url = Config::get('web_path') . Config::get('theme_path') . '/images/icons/' . $hover_icon; $hov_url = Config::get('web_path') . Config::get('theme_path') . '/images/icons/' . $hover_icon;
} }
else { else {
$hov_url = Config::get('web_path') . '/images/' . $hover_icon; $hov_url = Config::get('web_path') . '/images/' . $hover_icon;
} }
$hov_txt = "onmouseover=\"this.src='$hov_url'; return true;\" onmouseout=\"this.src='$img_url'; return true;\""; $hov_txt = "onmouseover=\"this.src='$hov_url'; return true;\" onmouseout=\"this.src='$img_url'; return true;\"";
} // end hover } // end hover
@ -676,14 +676,14 @@ function get_user_icon($name,$title='',$id='') {
/** /**
* xml_from_array * xml_from_array
* This takes a one dimensional array and * This takes a one dimensional array and
* creates a XML document form it for use * creates a XML document form it for use
* primarly by the ajax mojo * primarly by the ajax mojo
*/ */
function xml_from_array($array,$callback=0,$type='') { function xml_from_array($array,$callback=0,$type='') {
// If we weren't passed an array then return a blank string // If we weren't passed an array then return a blank string
if (!is_array($array)) { return ''; } if (!is_array($array)) { return ''; }
// The type is used for the different XML docs we pass // The type is used for the different XML docs we pass
switch ($type) { switch ($type) {
@ -732,19 +732,19 @@ function xml_from_array($array,$callback=0,$type='') {
return $string; return $string;
break; break;
default: default:
foreach ($array as $key=>$value) { foreach ($array as $key=>$value) {
if (is_numeric($key)) { $key = 'item'; } if (is_numeric($key)) { $key = 'item'; }
if (is_array($value)) { if (is_array($value)) {
$value = xml_from_array($value,1); $value = xml_from_array($value,1);
$string .= "\t<content div=\"$key\">$value</content>\n"; $string .= "\t<content div=\"$key\">$value</content>\n";
} }
else { else {
/* We need to escape the value */ /* We need to escape the value */
$string .= "\t<content div=\"$key\"><![CDATA[$value]]></content>\n"; $string .= "\t<content div=\"$key\"><![CDATA[$value]]></content>\n";
} }
// end foreach elements // end foreach elements
} }
if (!$callback) { if (!$callback) {
$string = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<root>\n" . $string . "</root>\n"; $string = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<root>\n" . $string . "</root>\n";
} }
@ -755,7 +755,7 @@ function xml_from_array($array,$callback=0,$type='') {
/** /**
* xml_get_header * xml_get_header
* This takes the type and returns the correct xml header * This takes the type and returns the correct xml header
*/ */
function xml_get_header($type){ function xml_get_header($type){
switch ($type){ switch ($type){
@ -776,18 +776,18 @@ function xml_get_header($type){
break; break;
case 'xspf': case 'xspf':
$header = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" . $header = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" .
"<!-- XML Generated by Ampache v." . Config::get('version') . " -->"; "<!-- XML Generated by Ampache v." . Config::get('version') . " -->";
"<playlist version = \"1\" xmlns=\"http://xspf.org/ns/0/\">\n ". "<playlist version = \"1\" xmlns=\"http://xspf.org/ns/0/\">\n ".
"<title>Ampache XSPF Playlist</title>\n" . "<title>Ampache XSPF Playlist</title>\n" .
"<creator>" . Config::get('site_title') . "</creator>\n" . "<creator>" . Config::get('site_title') . "</creator>\n" .
"<annotation>" . Config::get('site_title') . "</annotation>\n" . "<annotation>" . Config::get('site_title') . "</annotation>\n" .
"<info>". Config::get('web_path') ."</info>\n" . "<info>". Config::get('web_path') ."</info>\n" .
"<trackList>\n\n\n\n"; "<trackList>\n\n\n\n";
return $header; return $header;
break; break;
default: default:
$header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; $header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
return $header; return $header;
break; break;
} }
} //xml_get_header } //xml_get_header
@ -821,14 +821,14 @@ function xml_get_footer($type){
* on the specified require, only works if you * on the specified require, only works if you
* don't need to pass data in * don't need to pass data in
*/ */
function ajax_include($include) { function ajax_include($include) {
ob_start(); ob_start();
require_once Config::get('prefix') . '/templates/' . $include; require_once Config::get('prefix') . '/templates/' . $include;
$results = ob_get_contents(); $results = ob_get_contents();
ob_end_clean(); ob_end_clean();
return $results; return $results;
} // ajax_include } // ajax_include
@ -836,11 +836,11 @@ function ajax_include($include) {
* toggle_visible * toggle_visible
* this is identicla to the javascript command that it actually calls * this is identicla to the javascript command that it actually calls
*/ */
function toggle_visible($element) { function toggle_visible($element) {
echo "<script type=\"text/javascript\">\n"; echo "<script type=\"text/javascript\">\n";
echo "toggle_visible('$element');"; echo "toggle_visible('$element');";
echo "\n</script>\n"; echo "\n</script>\n";
} // toggle_visible } // toggle_visible
@ -849,14 +849,14 @@ function toggle_visible($element) {
* This shows the now playing templates and does some garbage colleciont * This shows the now playing templates and does some garbage colleciont
* this should really be somewhere else * this should really be somewhere else
*/ */
function show_now_playing() { function show_now_playing() {
Stream::gc_session();
Stream::gc_now_playing();
$web_path = Config::get('web_path'); Stream::gc_session();
$results = Stream::get_now_playing(); Stream::gc_now_playing();
require_once Config::get('prefix') . '/templates/show_now_playing.inc.php';
$web_path = Config::get('web_path');
$results = Stream::get_now_playing();
require_once Config::get('prefix') . '/templates/show_now_playing.inc.php';
} // show_now_playing } // show_now_playing

View file

@ -15,7 +15,7 @@
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/ */
@ -27,9 +27,9 @@
class AmpacheHttpq extends localplay_controller { class AmpacheHttpq extends localplay_controller {
/* Variables */ /* Variables */
private $version = '000001'; private $version = '000001';
private $description = 'Controls a Httpq instance, requires Ampaches Httpq version'; private $description = 'Controls a Httpq instance, requires Ampaches Httpq version';
/* Constructed variables */ /* Constructed variables */
private $_httpq; private $_httpq;
@ -39,8 +39,8 @@ class AmpacheHttpq extends localplay_controller {
* This returns the array map for the localplay object * This returns the array map for the localplay object
* REQUIRED for Localplay * REQUIRED for Localplay
*/ */
public function __construct() { public function __construct() {
/* Do a Require Once On the needed Libraries */ /* Do a Require Once On the needed Libraries */
require_once Config::get('prefix') . '/modules/httpq/httpqplayer.class.php'; require_once Config::get('prefix') . '/modules/httpq/httpqplayer.class.php';
@ -50,19 +50,19 @@ class AmpacheHttpq extends localplay_controller {
* get_description * get_description
* This returns the description of this localplay method * This returns the description of this localplay method
*/ */
public function get_description() { public function get_description() {
return $this->description;
return $this->description;
} // get_description } // get_description
/** /**
* get_version * get_version
* This returns the current version * This returns the current version
*/ */
public function get_version() { public function get_version() {
return $this->version; return $this->version;
} // get_version } // get_version
@ -72,10 +72,10 @@ class AmpacheHttpq extends localplay_controller {
*/ */
public function is_installed() { public function is_installed() {
$sql = "DESCRIBE `localplay_httpq`"; $sql = "DESCRIBE `localplay_httpq`";
$db_results = Dba::query($sql); $db_results = Dba::read($sql);
return Dba::num_rows($db_results); return Dba::num_rows($db_results);
} // is_installed } // is_installed
@ -85,38 +85,38 @@ class AmpacheHttpq extends localplay_controller {
* This function installs the MPD localplay controller * This function installs the MPD localplay controller
*/ */
public function install() { public function install() {
$sql = "CREATE TABLE `localplay_httpq` (`id` INT( 11 ) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY , ". $sql = "CREATE TABLE `localplay_httpq` (`id` INT( 11 ) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY , ".
"`name` VARCHAR( 128 ) COLLATE utf8_unicode_ci NOT NULL , " . "`name` VARCHAR( 128 ) COLLATE utf8_unicode_ci NOT NULL , " .
"`owner` INT( 11 ) NOT NULL, " . "`owner` INT( 11 ) NOT NULL, " .
"`host` VARCHAR( 255 ) COLLATE utf8_unicode_ci NOT NULL , " . "`host` VARCHAR( 255 ) COLLATE utf8_unicode_ci NOT NULL , " .
"`port` INT( 11 ) UNSIGNED NOT NULL , " . "`port` INT( 11 ) UNSIGNED NOT NULL , " .
"`password` VARCHAR( 255 ) COLLATE utf8_unicode_ci NOT NULL , " . "`password` VARCHAR( 255 ) COLLATE utf8_unicode_ci NOT NULL , " .
"`access` SMALLINT( 4 ) UNSIGNED NOT NULL DEFAULT '0'" . "`access` SMALLINT( 4 ) UNSIGNED NOT NULL DEFAULT '0'" .
") ENGINE = MYISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; ") ENGINE = MYISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
$db_results = Dba::query($sql); $db_results = Dba::write($sql);
// Add an internal preference for the users current active instance // Add an internal preference for the users current active instance
Preference::insert('httpq_active','HTTPQ Active Instance','0','25','integer','internal'); Preference::insert('httpq_active','HTTPQ Active Instance','0','25','integer','internal');
User::rebuild_all_preferences(); User::rebuild_all_preferences();
return true; return true;
} // install } // install
/** /**
* uninstall * uninstall
* This removes the localplay controller * This removes the localplay controller
*/ */
public function uninstall() { public function uninstall() {
$sql = "DROP TABLE `localplay_httpq`"; $sql = "DROP TABLE `localplay_httpq`";
$db_results = Dba::query($sql); $db_results = Dba::write($sql);
// Remove the pref we added for this // Remove the pref we added for this
Preference::delete('httpq_active'); Preference::delete('httpq_active');
return true; return true;
} // uninstall } // uninstall
@ -127,28 +127,28 @@ class AmpacheHttpq extends localplay_controller {
public function add_instance($data) { public function add_instance($data) {
// Foreach and clean up what we need // Foreach and clean up what we need
foreach ($data as $key=>$value) { foreach ($data as $key=>$value) {
switch ($key) { switch ($key) {
case 'name': case 'name':
case 'host': case 'host':
case 'port': case 'port':
case 'password': case 'password':
${$key} = Dba::escape($value); ${$key} = Dba::escape($value);
break; break;
default: default:
// Rien a faire // Rien a faire
break; break;
} // end switch on key } // end switch on key
} // end foreach } // end foreach
$user_id = Dba::escape($GLOBALS['user']->id); $user_id = Dba::escape($GLOBALS['user']->id);
$sql = "INSERT INTO `localplay_httpq` (`name`,`host`,`port`,`password`,`owner`) " . $sql = "INSERT INTO `localplay_httpq` (`name`,`host`,`port`,`password`,`owner`) " .
"VALUES ('$name','$host','$port','$password','$user_id')"; "VALUES ('$name','$host','$port','$password','$user_id')";
$db_results = Dba::query($sql); $db_results = Dba::write($sql);
return $db_results; return $db_results;
} // add_instance } // add_instance
@ -158,32 +158,32 @@ class AmpacheHttpq extends localplay_controller {
*/ */
public function delete_instance($uid) { public function delete_instance($uid) {
$uid = Dba::escape($uid); $uid = Dba::escape($uid);
$sql = "DELETE FROM `localplay_httpq` WHERE `id`='$uid'"; $sql = "DELETE FROM `localplay_httpq` WHERE `id`='$uid'";
$db_results = Dba::query($sql); $db_results = Dba::write($sql);
return true; return true;
} // delete_instance } // delete_instance
/** /**
* get_instances * get_instances
* This returns a key'd array of the instance information with * This returns a key'd array of the instance information with
* [UID]=>[NAME] * [UID]=>[NAME]
*/ */
public function get_instances() { public function get_instances() {
$sql = "SELECT * FROM `localplay_httpq` ORDER BY `name`"; $sql = "SELECT * FROM `localplay_httpq` ORDER BY `name`";
$db_results = Dba::query($sql); $db_results = Dba::read($sql);
$results = array(); $results = array();
while ($row = Dba::fetch_assoc($db_results)) { while ($row = Dba::fetch_assoc($db_results)) {
$results[$row['id']] = $row['name']; $results[$row['id']] = $row['name'];
} }
return $results; return $results;
} // get_instances } // get_instances
@ -191,18 +191,18 @@ class AmpacheHttpq extends localplay_controller {
* update_instance * update_instance
* This takes an ID and an array of data and updates the instance specified * This takes an ID and an array of data and updates the instance specified
*/ */
public function update_instance($uid,$data) { public function update_instance($uid,$data) {
$uid = Dba::escape($uid); $uid = Dba::escape($uid);
$port = Dba::escape($data['port']); $port = Dba::escape($data['port']);
$host = Dba::escape($data['host']); $host = Dba::escape($data['host']);
$name = Dba::escape($data['name']); $name = Dba::escape($data['name']);
$pass = Dba::escape($data['password']); $pass = Dba::escape($data['password']);
$sql = "UPDATE `localplay_httpq` SET `host`='$host', `port`='$port', `name`='$name', `password`='$pass' WHERE `id`='$uid'";
$db_results = Dba::query($sql);
return true; $sql = "UPDATE `localplay_httpq` SET `host`='$host', `port`='$port', `name`='$name', `password`='$pass' WHERE `id`='$uid'";
$db_results = Dba::write($sql);
return true;
} // update_instance } // update_instance
@ -218,25 +218,25 @@ class AmpacheHttpq extends localplay_controller {
$fields['port'] = array('description'=>_('Port'),'type'=>'textbox'); $fields['port'] = array('description'=>_('Port'),'type'=>'textbox');
$fields['password'] = array('description'=>_('Password'),'type'=>'textbox'); $fields['password'] = array('description'=>_('Password'),'type'=>'textbox');
return $fields; return $fields;
} // instance_fields } // instance_fields
/** /**
* get_instance * get_instance
* This returns a single instance and all it's variables * This returns a single instance and all it's variables
*/ */
public function get_instance($instance='') { public function get_instance($instance='') {
$instance = $instance ? $instance : Config::get('httpq_active'); $instance = $instance ? $instance : Config::get('httpq_active');
$instance = Dba::escape($instance); $instance = Dba::escape($instance);
$sql = "SELECT * FROM `localplay_httpq` WHERE `id`='$instance'"; $sql = "SELECT * FROM `localplay_httpq` WHERE `id`='$instance'";
$db_results = Dba::query($sql); $db_results = Dba::read($sql);
$row = Dba::fetch_assoc($db_results); $row = Dba::fetch_assoc($db_results);
return $row; return $row;
} // get_instance } // get_instance
@ -247,18 +247,18 @@ class AmpacheHttpq extends localplay_controller {
public function set_active_instance($uid,$user_id='') { public function set_active_instance($uid,$user_id='') {
// Not an admin? bubkiss! // Not an admin? bubkiss!
if (!$GLOBALS['user']->has_access('100')) { if (!$GLOBALS['user']->has_access('100')) {
$user_id = $GLOBALS['user']->id; $user_id = $GLOBALS['user']->id;
} }
$user_id = $user_id ? $user_id : $GLOBALS['user']->id; $user_id = $user_id ? $user_id : $GLOBALS['user']->id;
Preference::update('httpq_active',$user_id,intval($uid)); Preference::update('httpq_active',$user_id,intval($uid));
Config::set('httpq_active',intval($uid),'1'); Config::set('httpq_active',intval($uid),'1');
return true; return true;
} // set_active_instance } // set_active_instance
/** /**
* get_active_instance * get_active_instance
@ -275,16 +275,16 @@ class AmpacheHttpq extends localplay_controller {
* This must take an array of URL's from Ampache * This must take an array of URL's from Ampache
* and then add them to HttpQ * and then add them to HttpQ
*/ */
public function add($object) { public function add($object) {
$url = $this->get_url($object); $url = $this->get_url($object);
// Try to pass a title (if we can) // Try to pass a title (if we can)
if (is_object($object)) { if (is_object($object)) {
$title = $object->title; $title = $object->title;
} }
if (is_null($this->_httpq->add($title,$url))) { if (is_null($this->_httpq->add($title,$url))) {
debug_event('httpq_add',"Error: Unable to add $url to Httpq",'1'); debug_event('httpq_add',"Error: Unable to add $url to Httpq",'1');
} }
@ -297,27 +297,27 @@ class AmpacheHttpq extends localplay_controller {
* This must take an array of ID's (as passed by get function) from Ampache * This must take an array of ID's (as passed by get function) from Ampache
* and delete them from Httpq * and delete them from Httpq
*/ */
public function delete_track($object_id) { public function delete_track($object_id) {
if (is_null($this->_httpq->delete_pos($object_id))) { if (is_null($this->_httpq->delete_pos($object_id))) {
debug_event('httpq_del','ERROR Unable to delete ' . $object_id . ' from Httpq','1'); debug_event('httpq_del','ERROR Unable to delete ' . $object_id . ' from Httpq','1');
return false; return false;
} }
return true; return true;
} // delete_track } // delete_track
/** /**
* clear_playlist * clear_playlist
* This deletes the entire Httpq playlist... nuff said * This deletes the entire Httpq playlist... nuff said
*/ */
public function clear_playlist() { public function clear_playlist() {
if (is_null($this->_httpq->clear())) { return false; } if (is_null($this->_httpq->clear())) { return false; }
// If the clear worked we should stop it! // If the clear worked we should stop it!
$this->stop(); $this->stop();
return true; return true;
@ -328,15 +328,15 @@ class AmpacheHttpq extends localplay_controller {
* This just tells HttpQ to start playing, it does not * This just tells HttpQ to start playing, it does not
* take any arguments * take any arguments
*/ */
public function play() { public function play() {
/* A play when it's already playing causes a track restart /* A play when it's already playing causes a track restart
* which we don't want to doublecheck its state * which we don't want to doublecheck its state
*/ */
if ($this->_httpq->state() == 'play') { if ($this->_httpq->state() == 'play') {
return true; return true;
} }
if (is_null($this->_httpq->play())) { return false; } if (is_null($this->_httpq->play())) { return false; }
return true; return true;
} // play } // play
@ -346,9 +346,9 @@ class AmpacheHttpq extends localplay_controller {
* This just tells HttpQ to stop playing, it does not take * This just tells HttpQ to stop playing, it does not take
* any arguments * any arguments
*/ */
public function stop() { public function stop() {
if (is_null($this->_httpq->stop())) { return false; } if (is_null($this->_httpq->stop())) { return false; }
return true; return true;
} // stop } // stop
@ -357,19 +357,19 @@ class AmpacheHttpq extends localplay_controller {
* skip * skip
* This tells HttpQ to skip to the specified song * This tells HttpQ to skip to the specified song
*/ */
public function skip($song) { public function skip($song) {
if (is_null($this->_httpq->skip($song))) { return false; } if (is_null($this->_httpq->skip($song))) { return false; }
return true; return true;
} // skip } // skip
/** /**
* This tells Httpq to increase the volume by WinAmps default amount * This tells Httpq to increase the volume by WinAmps default amount
*/ */
public function volume_up() { public function volume_up() {
if (is_null($this->_httpq->volume_up())) { return false; } if (is_null($this->_httpq->volume_up())) { return false; }
return true; return true;
} // volume_up } // volume_up
@ -377,20 +377,20 @@ class AmpacheHttpq extends localplay_controller {
/** /**
* This tells HttpQ to decrease the volume by Winamps default amount * This tells HttpQ to decrease the volume by Winamps default amount
*/ */
public function volume_down() { public function volume_down() {
if (is_null($this->_httpq->volume_down())) { return false; } if (is_null($this->_httpq->volume_down())) { return false; }
return true; return true;
} // volume_down } // volume_down
/** /**
* next * next
* This just tells HttpQ to skip to the next song * This just tells HttpQ to skip to the next song
*/ */
public function next() { public function next() {
if (is_null($this->_httpq->next())) { return false; } if (is_null($this->_httpq->next())) { return false; }
return true; return true;
@ -400,24 +400,24 @@ class AmpacheHttpq extends localplay_controller {
* prev * prev
* This just tells HttpQ to skip to the prev song * This just tells HttpQ to skip to the prev song
*/ */
public function prev() { public function prev() {
if (is_null($this->_httpq->prev())) { return false; } if (is_null($this->_httpq->prev())) { return false; }
return true; return true;
} // prev } // prev
/** /**
* pause * pause
* This tells HttpQ to pause the current song * This tells HttpQ to pause the current song
*/ */
public function pause() { public function pause() {
if (is_null($this->_httpq->pause())) { return false; } if (is_null($this->_httpq->pause())) { return false; }
return true; return true;
} // pause } // pause
/** /**
* volume * volume
@ -436,7 +436,7 @@ class AmpacheHttpq extends localplay_controller {
* This tells HttpQ to set the repeating the playlist (i.e. loop) to either on or off * This tells HttpQ to set the repeating the playlist (i.e. loop) to either on or off
*/ */
public function repeat($state) { public function repeat($state) {
if (is_null($this->_httpq->repeat($state))) { return false; } if (is_null($this->_httpq->repeat($state))) { return false; }
return true; return true;
@ -459,23 +459,23 @@ class AmpacheHttpq extends localplay_controller {
* The songs that HttpQ currently has in it's playlist. This must be * The songs that HttpQ currently has in it's playlist. This must be
* done in a standardized fashion * done in a standardized fashion
*/ */
public function get() { public function get() {
/* Get the Current Playlist */ /* Get the Current Playlist */
$list = $this->_httpq->get_tracks(); $list = $this->_httpq->get_tracks();
if (!$list) { return array(); } if (!$list) { return array(); }
$songs = explode("::",$list);
foreach ($songs as $key=>$entry) { $songs = explode("::",$list);
foreach ($songs as $key=>$entry) {
$data = array(); $data = array();
/* Required Elements */ /* Required Elements */
$data['id'] = $key; $data['id'] = $key;
$data['raw'] = $entry; $data['raw'] = $entry;
$url_data = $this->parse_url($entry); $url_data = $this->parse_url($entry);
switch ($url_data['primary_key']) { switch ($url_data['primary_key']) {
case 'oid': case 'oid':
$song = new Song($url_data['oid']); $song = new Song($url_data['oid']);
@ -488,10 +488,10 @@ class AmpacheHttpq extends localplay_controller {
$data['name'] = _('Democratic') . ' - ' . $democratic->name; $data['name'] = _('Democratic') . ' - ' . $democratic->name;
$data['link'] = ''; $data['link'] = '';
break; break;
case 'random': case 'random':
$data['name'] = _('Random') . ' - ' . scrub_out(ucfirst($url_data['type'])); $data['name'] = _('Random') . ' - ' . scrub_out(ucfirst($url_data['type']));
$data['link'] = ''; $data['link'] = '';
break; break;
default: default:
/* If we don't know it, look up by filename */ /* If we don't know it, look up by filename */
$filename = Dba::escape($entry['file']); $filename = Dba::escape($entry['file']);
@ -512,14 +512,14 @@ class AmpacheHttpq extends localplay_controller {
$frequency = $media->frequency ? '[' . $media->frequency . ']' : ''; $frequency = $media->frequency ? '[' . $media->frequency . ']' : '';
$site_url = $media->site_url ? '(' . $media->site_url . ')' : ''; $site_url = $media->site_url ? '(' . $media->site_url . ')' : '';
$data['name'] = "$media->name $frequency $site_url"; $data['name'] = "$media->name $frequency $site_url";
$data['link'] = $media->site_url; $data['link'] = $media->site_url;
break; break;
} // end switch on type } // end switch on type
} // end if results } // end if results
else { else {
$data['name'] = basename($data['raw']); $data['name'] = basename($data['raw']);
$data['link'] = basename($data['raw']); $data['link'] = basename($data['raw']);
} }
break; break;
} // end switch on primary key type } // end switch on primary key type
@ -529,7 +529,7 @@ class AmpacheHttpq extends localplay_controller {
$results[] = $data; $results[] = $data;
} // foreach playlist items } // foreach playlist items
return $results; return $results;
} // get } // get
@ -539,7 +539,7 @@ class AmpacheHttpq extends localplay_controller {
* This returns bool/int values for features, loop, repeat and any other features * This returns bool/int values for features, loop, repeat and any other features
* That this localplay method supports. required function * That this localplay method supports. required function
*/ */
public function status() { public function status() {
/* Construct the Array */ /* Construct the Array */
$array['state'] = $this->_httpq->state(); $array['state'] = $this->_httpq->state();
@ -547,17 +547,17 @@ class AmpacheHttpq extends localplay_controller {
$array['repeat'] = $this->_httpq->get_repeat(); $array['repeat'] = $this->_httpq->get_repeat();
$array['random'] = $this->_httpq->get_random(); $array['random'] = $this->_httpq->get_random();
$array['track'] = $this->_httpq->get_now_playing(); $array['track'] = $this->_httpq->get_now_playing();
$url_data = $this->parse_url($array['track']); $url_data = $this->parse_url($array['track']);
if (isset($url_data['oid'])) { if (isset($url_data['oid'])) {
$song = new Song($url_data['oid']); $song = new Song($url_data['oid']);
$array['track_title'] = $song->title; $array['track_title'] = $song->title;
$array['track_artist'] = $song->get_artist_name(); $array['track_artist'] = $song->get_artist_name();
$array['track_album'] = $song->get_album_name(); $array['track_album'] = $song->get_album_name();
} }
else { else {
$array['track_title'] = basename($array['track']); $array['track_title'] = basename($array['track']);
} }
return $array; return $array;
@ -569,18 +569,18 @@ class AmpacheHttpq extends localplay_controller {
* a boolean value for the status, to save time this handle * a boolean value for the status, to save time this handle
* is stored in this class * is stored in this class
*/ */
public function connect() { public function connect() {
$options = self::get_instance(); $options = self::get_instance();
$this->_httpq = new HttpQPlayer($options['host'],$options['password'],$options['port']); $this->_httpq = new HttpQPlayer($options['host'],$options['password'],$options['port']);
// Test our connection by retriving the version // Test our connection by retriving the version
if (!is_null($this->_httpq->version())) { return true; } if (!is_null($this->_httpq->version())) { return true; }
return false; return false;
} // connect } // connect
} //end of AmpacheHttpq } //end of AmpacheHttpq
?> ?>

View file

@ -72,7 +72,7 @@ class AmpacheMpd extends localplay_controller {
public function is_installed() { public function is_installed() {
$sql = "DESCRIBE `localplay_mpd`"; $sql = "DESCRIBE `localplay_mpd`";
$db_results = Dba::query($sql); $db_results = Dba::read($sql);
return Dba::num_rows($db_results); return Dba::num_rows($db_results);
@ -93,7 +93,7 @@ class AmpacheMpd extends localplay_controller {
"`password` VARCHAR( 255 ) COLLATE utf8_unicode_ci NOT NULL , " . "`password` VARCHAR( 255 ) COLLATE utf8_unicode_ci NOT NULL , " .
"`access` SMALLINT( 4 ) UNSIGNED NOT NULL DEFAULT '0'" . "`access` SMALLINT( 4 ) UNSIGNED NOT NULL DEFAULT '0'" .
") ENGINE = MYISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; ") ENGINE = MYISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
$db_results = Dba::query($sql); $db_results = Dba::write($sql);
// Add an internal preference for the users current active instance // Add an internal preference for the users current active instance
Preference::insert('mpd_active','MPD Active Instance','0','25','integer','internal'); Preference::insert('mpd_active','MPD Active Instance','0','25','integer','internal');
@ -110,7 +110,7 @@ class AmpacheMpd extends localplay_controller {
public function uninstall() { public function uninstall() {
$sql = "DROP TABLE `localplay_mpd`"; $sql = "DROP TABLE `localplay_mpd`";
$db_results = Dba::query($sql); $db_results = Dba::write($sql);
Preference::delete('mpd_active'); Preference::delete('mpd_active');
@ -142,7 +142,7 @@ class AmpacheMpd extends localplay_controller {
$sql = "INSERT INTO `localplay_mpd` (`name`,`host`,`port`,`password`,`owner`) " . $sql = "INSERT INTO `localplay_mpd` (`name`,`host`,`port`,`password`,`owner`) " .
"VALUES ('$name','$host','$port','$password','$user_id')"; "VALUES ('$name','$host','$port','$password','$user_id')";
$db_results = Dba::query($sql); $db_results = Dba::write($sql);
return $db_results; return $db_results;
@ -158,7 +158,7 @@ class AmpacheMpd extends localplay_controller {
// Go ahead and delete this mofo! // Go ahead and delete this mofo!
$sql = "DELETE FROM `localplay_mpd` WHERE `id`='$uid'"; $sql = "DELETE FROM `localplay_mpd` WHERE `id`='$uid'";
$db_results = Dba::query($sql); $db_results = Dba::write($sql);
return true; return true;
@ -172,7 +172,7 @@ class AmpacheMpd extends localplay_controller {
public function get_instances() { public function get_instances() {
$sql = "SELECT * FROM `localplay_mpd` ORDER BY `name`"; $sql = "SELECT * FROM `localplay_mpd` ORDER BY `name`";
$db_results = Dba::query($sql); $db_results = Dba::read($sql);
$results = array(); $results = array();
@ -195,7 +195,7 @@ class AmpacheMpd extends localplay_controller {
$instance = Dba::escape($instance); $instance = Dba::escape($instance);
$sql = "SELECT * FROM `localplay_mpd` WHERE `id`='$instance'"; $sql = "SELECT * FROM `localplay_mpd` WHERE `id`='$instance'";
$db_results = Dba::query($sql); $db_results = Dba::read($sql);
$row = Dba::fetch_assoc($db_results); $row = Dba::fetch_assoc($db_results);
@ -216,7 +216,7 @@ class AmpacheMpd extends localplay_controller {
$pass = Dba::escape($data['password']); $pass = Dba::escape($data['password']);
$sql = "UPDATE `localplay_mpd` SET `host`='$host', `port`='$port', `name`='$name', `password`='$pass' WHERE `id`='$uid'"; $sql = "UPDATE `localplay_mpd` SET `host`='$host', `port`='$port', `name`='$name', `password`='$pass' WHERE `id`='$uid'";
$db_results = Dba::query($sql); $db_results = Dba::write($sql);
return true; return true;

View file

@ -15,38 +15,38 @@
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/ */
/** /**
* AmpacheShoutCast * AmpacheShoutCast
* This class handles the shoutcast extension this is kind of an ugly controller * This class handles the shoutcast extension this is kind of an ugly controller
* ooh well you do what you can * ooh well you do what you can
*/ */
class AmpacheShoutCast extends localplay_controller { class AmpacheShoutCast extends localplay_controller {
/* Variables */ /* Variables */
private $version = '000001'; private $version = '000001';
private $description = 'Outputs to a local shoutcast server'; private $description = 'Outputs to a local shoutcast server';
private $local_path; private $local_path;
private $pid; private $pid;
private $playlist; private $playlist;
// Generated // Generated
private $files = array(); private $files = array();
/** /**
* Constructor * Constructor
* This returns the array map for the localplay object * This returns the array map for the localplay object
* REQUIRED for Localplay * REQUIRED for Localplay
*/ */
public function __construct() { public function __construct() {
} // AmpacheShoutCast } // AmpacheShoutCast
@ -54,19 +54,19 @@ class AmpacheShoutCast extends localplay_controller {
* get_description * get_description
* Returns the description * Returns the description
*/ */
public function get_description() { public function get_description() {
return $this->description;
return $this->description;
} // get_description } // get_description
/** /**
* get_version * get_version
* This returns the version information * This returns the version information
*/ */
public function get_version() { public function get_version() {
return $this->version; return $this->version;
} // get_version } // get_version
@ -74,10 +74,10 @@ class AmpacheShoutCast extends localplay_controller {
* is_installed * is_installed
* This returns true or false if MPD controller is installed * This returns true or false if MPD controller is installed
*/ */
public function is_installed() { public function is_installed() {
$sql = "DESCRIBE `localplay_shoutcast`"; $sql = "DESCRIBE `localplay_shoutcast`";
$db_results = Dba::query($sql); $db_results = Dba::read($sql);
return Dba::num_rows($db_results); return Dba::num_rows($db_results);
@ -87,7 +87,7 @@ class AmpacheShoutCast extends localplay_controller {
* install * install
* This function installs the MPD localplay controller * This function installs the MPD localplay controller
*/ */
public function install() { public function install() {
/* We need to create the MPD table */ /* We need to create the MPD table */
$sql = "CREATE TABLE `localplay_shoutcast` ( `id` INT( 11 ) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY , " . $sql = "CREATE TABLE `localplay_shoutcast` ( `id` INT( 11 ) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY , " .
@ -98,11 +98,11 @@ class AmpacheShoutCast extends localplay_controller {
"`local_root` VARCHAR( 255 ) COLLATE utf8_unicode_ci NOT NULL , " . "`local_root` VARCHAR( 255 ) COLLATE utf8_unicode_ci NOT NULL , " .
"`access` SMALLINT( 4 ) UNSIGNED NOT NULL DEFAULT '0'" . "`access` SMALLINT( 4 ) UNSIGNED NOT NULL DEFAULT '0'" .
") ENGINE = MYISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; ") ENGINE = MYISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
$db_results = Dba::query($sql); $db_results = Dba::write($sql);
// Add an internal preference for the users current active instance // Add an internal preference for the users current active instance
Preference::insert('shoutcast_active','Shoutcast Active Instance','0','25','integer','internal'); Preference::insert('shoutcast_active','Shoutcast Active Instance','0','25','integer','internal');
User::rebuild_all_preferences(); User::rebuild_all_preferences();
return true; return true;
@ -110,14 +110,14 @@ class AmpacheShoutCast extends localplay_controller {
/** /**
* uninstall * uninstall
* This removes the localplay controller * This removes the localplay controller
*/ */
public function uninstall() { public function uninstall() {
$sql = "DROP TABLE `localplay_shoutcast`"; $sql = "DROP TABLE `localplay_shoutcast`";
$db_results = Dba::query($sql); $db_results = Dba::write($sql);
Preference::delete('shoutcast_active'); Preference::delete('shoutcast_active');
return true; return true;
@ -127,29 +127,29 @@ class AmpacheShoutCast extends localplay_controller {
* add_instance * add_instance
* This takes key'd data and inserts a new MPD instance * This takes key'd data and inserts a new MPD instance
*/ */
public function add_instance($data) { public function add_instance($data) {
foreach ($data as $key=>$value) { foreach ($data as $key=>$value) {
switch ($key) { switch ($key) {
case 'name': case 'name':
case 'pid': case 'pid':
case 'playlist': case 'playlist':
case 'local_root': case 'local_root':
${$key} = Dba::escape($value); ${$key} = Dba::escape($value);
break; break;
default: default:
break; break;
} // end switch } // end switch
} // end foreach } // end foreach
$user_id = Dba::escape($GLOBALS['user']->id); $user_id = Dba::escape($GLOBALS['user']->id);
$sql = "INSERT INTO `localplay_shoutcast` (`name`,`pid`,`playlist`,`local_root`,`owner`) " . $sql = "INSERT INTO `localplay_shoutcast` (`name`,`pid`,`playlist`,`local_root`,`owner`) " .
"VALUES ('$name','$pid','$playlist','$local_root','$user_id')"; "VALUES ('$name','$pid','$playlist','$local_root','$user_id')";
$db_results = Dba::query($sql); $db_results = Dba::write($sql);
return $db_results; return $db_results;
} // add_instance } // add_instance
@ -157,35 +157,35 @@ class AmpacheShoutCast extends localplay_controller {
* delete_instance * delete_instance
* This takes a UID and deletes the instance in question * This takes a UID and deletes the instance in question
*/ */
public function delete_instance($uid) { public function delete_instance($uid) {
$uid = Dba::escape($uid); $uid = Dba::escape($uid);
// Go ahead and delete this mofo! // Go ahead and delete this mofo!
$sql = "DELETE FROM `localplay_shoutcast` WHERE `id`='$uid'"; $sql = "DELETE FROM `localplay_shoutcast` WHERE `id`='$uid'";
$db_results = Dba::query($sql); $db_results = Dba::write($sql);
return true; return true;
} // delete_instance } // delete_instance
/** /**
* get_instances * get_instances
* This returns a key'd array of the instance information with * This returns a key'd array of the instance information with
* [UID]=>[NAME] * [UID]=>[NAME]
*/ */
public function get_instances() { public function get_instances() {
$sql = "SELECT * FROM `localplay_shoutcast` ORDER BY `name`"; $sql = "SELECT * FROM `localplay_shoutcast` ORDER BY `name`";
$db_results = Dba::query($sql); $db_results = Dba::read($sql);
$results = array(); $results = array();
while ($row = Dba::fetch_assoc($db_results)) { while ($row = Dba::fetch_assoc($db_results)) {
$results[$row['id']] = $row['name']; $results[$row['id']] = $row['name'];
} }
return $results; return $results;
} // get_instances } // get_instances
@ -194,17 +194,17 @@ class AmpacheShoutCast extends localplay_controller {
* This returns the specified instance and all it's pretty variables * This returns the specified instance and all it's pretty variables
* If no instance is passed current is used * If no instance is passed current is used
*/ */
public function get_instance($instance='') { public function get_instance($instance='') {
$instance = $instance ? $instance : Config::get('shoutcast_active'); $instance = $instance ? $instance : Config::get('shoutcast_active');
$instance = Dba::escape($instance); $instance = Dba::escape($instance);
$sql = "SELECT * FROM `localplay_shoutcast` WHERE `id`='$instance'"; $sql = "SELECT * FROM `localplay_shoutcast` WHERE `id`='$instance'";
$db_results = Dba::query($sql); $db_results = Dba::read($sql);
$row = Dba::fetch_assoc($db_results); $row = Dba::fetch_assoc($db_results);
return $row; return $row;
} // get_instance } // get_instance
@ -212,18 +212,18 @@ class AmpacheShoutCast extends localplay_controller {
* update_instance * update_instance
* This takes an ID and an array of data and updates the instance specified * This takes an ID and an array of data and updates the instance specified
*/ */
public function update_instance($uid,$data) { public function update_instance($uid,$data) {
$uid = Dba::escape($uid); $uid = Dba::escape($uid);
$pid = Dba::escape($data['pid']); $pid = Dba::escape($data['pid']);
$playlist = Dba::escape($data['playlist']); $playlist = Dba::escape($data['playlist']);
$name = Dba::escape($data['name']); $name = Dba::escape($data['name']);
$local_root = Dba::escape($data['local_root']); $local_root = Dba::escape($data['local_root']);
$sql = "UPDATE `localplay_shoutcast` SET `pid`='$pid', `playlist`='$playlist', `name`='$name', `local_root`='$local_root' WHERE `id`='$uid'"; $sql = "UPDATE `localplay_shoutcast` SET `pid`='$pid', `playlist`='$playlist', `name`='$name', `local_root`='$local_root' WHERE `id`='$uid'";
$db_results = Dba::query($sql); $db_results = Dba::write($sql);
return true; return true;
} // update_instance } // update_instance
@ -232,14 +232,14 @@ class AmpacheShoutCast extends localplay_controller {
* This returns a key'd array of [NAME]=>array([DESCRIPTION]=>VALUE,[TYPE]=>VALUE) for the * This returns a key'd array of [NAME]=>array([DESCRIPTION]=>VALUE,[TYPE]=>VALUE) for the
* fields so that we can on-the-fly generate a form * fields so that we can on-the-fly generate a form
*/ */
public function instance_fields() { public function instance_fields() {
$fields['name'] = array('description'=>_('Instance Name'),'type'=>'textbox'); $fields['name'] = array('description'=>_('Instance Name'),'type'=>'textbox');
$fields['pid'] = array('description'=>_('PID File'),'type'=>'textbox'); $fields['pid'] = array('description'=>_('PID File'),'type'=>'textbox');
$fields['playlist'] = array('description'=>_('Playlist File'),'type'=>'textbox'); $fields['playlist'] = array('description'=>_('Playlist File'),'type'=>'textbox');
$fields['local_root'] = array('description'=>_('Local Path to Files'),'type'=>'textbox'); $fields['local_root'] = array('description'=>_('Local Path to Files'),'type'=>'textbox');
return $fields; return $fields;
} // instance_fields } // instance_fields
@ -247,64 +247,64 @@ class AmpacheShoutCast extends localplay_controller {
* set_active_instance * set_active_instance
* This sets the specified instance as the 'active' one * This sets the specified instance as the 'active' one
*/ */
public function set_active_instance($uid,$user_id='') { public function set_active_instance($uid,$user_id='') {
// Not an admin? bubkiss! // Not an admin? bubkiss!
if (!$GLOBALS['user']->has_access('100')) { if (!$GLOBALS['user']->has_access('100')) {
$user_id = $GLOBALS['user']->id; $user_id = $GLOBALS['user']->id;
} }
$user_id = $user_id ? $user_id : $GLOBALS['user']->id; $user_id = $user_id ? $user_id : $GLOBALS['user']->id;
Preference::update('shoutcast_active',$user_id,intval($uid)); Preference::update('shoutcast_active',$user_id,intval($uid));
Config::set('shoutcast_active',intval($uid),'1'); Config::set('shoutcast_active',intval($uid),'1');
return true; return true;
} // set_active_instance } // set_active_instance
/** /**
* get_active_instance * get_active_instance
* This returns the UID of the current active instance * This returns the UID of the current active instance
* false if none are active * false if none are active
*/ */
public function get_active_instance() { public function get_active_instance() {
} // get_active_instance } // get_active_instance
/** /**
* add * add
* This takes a single object and adds it in, it uses the built in * This takes a single object and adds it in, it uses the built in
* functions to generate the URL it needs * functions to generate the URL it needs
*/ */
public function add($object) { public function add($object) {
// Before we add this it must be a mp3 // Before we add this it must be a mp3
$object->format_type(); $object->format_type();
if ($object->mime != 'audio/mpeg') { if ($object->mime != 'audio/mpeg') {
debug_event('ShoutCast','Error: Unable to play ' . $this->mime . ' files with shoutcast, skipping','3'); debug_event('ShoutCast','Error: Unable to play ' . $this->mime . ' files with shoutcast, skipping','3');
return false; return false;
} }
if ($object->rate != '44100') { if ($object->rate != '44100') {
debug_event('Shoutcast','Error: Unable to play ' . $this->rate . ' files with shoutcast, skipping','3'); debug_event('Shoutcast','Error: Unable to play ' . $this->rate . ' files with shoutcast, skipping','3');
return false; return false;
} }
// Take the filename and strip off the catalog's root_path and put our // Take the filename and strip off the catalog's root_path and put our
// prefix onto it // prefix onto it
$filename = $object->file; $filename = $object->file;
$catalog = new Catalog($object->catalog); $catalog = new Catalog($object->catalog);
if ($this->local_path) { if ($this->local_path) {
$filename = str_replace($catalog->path,$this->local_path,$filename); $filename = str_replace($catalog->path,$this->local_path,$filename);
} }
$this->files[] = $filename; $this->files[] = $filename;
return true; return true;
} // add } // add
@ -313,17 +313,17 @@ class AmpacheShoutCast extends localplay_controller {
* This must take a single ID (as passed by get function) from Ampache * This must take a single ID (as passed by get function) from Ampache
* and delete it from the current playlist * and delete it from the current playlist
*/ */
public function delete_track($object_id) { public function delete_track($object_id) {
return true; return true;
} // delete_track } // delete_track
/** /**
* clear_playlist * clear_playlist
* This deletes the entire MPD playlist... nuff said * This deletes the entire MPD playlist... nuff said
*/ */
function clear_playlist() { function clear_playlist() {
return true; return true;
@ -334,16 +334,16 @@ class AmpacheShoutCast extends localplay_controller {
* This just tells MPD to start playing, it does not * This just tells MPD to start playing, it does not
* take any arguments * take any arguments
*/ */
public function play() { public function play() {
// If we have no files[] then just Reload the server nothing else // If we have no files[] then just Reload the server nothing else
if (!count($this->files)) { if (!count($this->files)) {
$this->send_command('reload'); $this->send_command('reload');
} }
else { else {
$this->write_playlist(); $this->write_playlist();
$this->send_command('reload'); $this->send_command('reload');
} }
return true; return true;
@ -353,9 +353,9 @@ class AmpacheShoutCast extends localplay_controller {
* stop * stop
* This just stops the shoutcast server * This just stops the shoutcast server
*/ */
public function stop() { public function stop() {
$this->send_command('stop'); $this->send_command('stop');
return true; return true;
} // stop } // stop
@ -364,16 +364,16 @@ class AmpacheShoutCast extends localplay_controller {
* skip * skip
* This tells MPD to skip to the specified song * This tells MPD to skip to the specified song
*/ */
function skip($song) { function skip($song) {
return true; return true;
} // skip } // skip
/** /**
* This tells MPD to increase the volume by 5 * This tells MPD to increase the volume by 5
*/ */
public function volume_up() { public function volume_up() {
return true; return true;
@ -382,19 +382,19 @@ class AmpacheShoutCast extends localplay_controller {
/** /**
* This tells MPD to decrese the volume by 5 * This tells MPD to decrese the volume by 5
*/ */
public function volume_down() { public function volume_down() {
return true; return true;
} // volume_down } // volume_down
/** /**
* next * next
* This just tells MPD to skip to the next song * This just tells MPD to skip to the next song
*/ */
public function next() { public function next() {
$this->send_command('next'); $this->send_command('next');
return true; return true;
} // next } // next
@ -403,20 +403,20 @@ class AmpacheShoutCast extends localplay_controller {
* prev * prev
* This just tells MPD to skip to the prev song * This just tells MPD to skip to the prev song
*/ */
public function prev() { public function prev() {
return true; return true;
} // prev } // prev
/** /**
* pause * pause
*/ */
public function pause() { public function pause() {
return true; return true;
} // pause } // pause
/** /**
* volume * volume
@ -433,7 +433,7 @@ class AmpacheShoutCast extends localplay_controller {
* This tells MPD to set the repeating the playlist (i.e. loop) to either on or off * This tells MPD to set the repeating the playlist (i.e. loop) to either on or off
*/ */
public function repeat($state) { public function repeat($state) {
return true; return true;
} // repeat } // repeat
@ -445,7 +445,7 @@ class AmpacheShoutCast extends localplay_controller {
*/ */
public function random($onoff) { public function random($onoff) {
$this->send_command('shuffle'); $this->send_command('shuffle');
return true; return true;
} // random } // random
@ -465,18 +465,18 @@ class AmpacheShoutCast extends localplay_controller {
* The songs that MPD currently has in it's playlist. This must be * The songs that MPD currently has in it's playlist. This must be
* done in a standardized fashion * done in a standardized fashion
*/ */
public function get() { public function get() {
$songs = $this->get_playlist(); $songs = $this->get_playlist();
foreach ($songs as $key=>$file) { foreach ($songs as $key=>$file) {
$data['id'] = $key; $data['id'] = $key;
$data['raw'] = $file; $data['raw'] = $file;
$data['name'] = $file; $data['name'] = $file;
$results[] = $data; $results[] = $data;
} }
return $results; return $results;
} // get } // get
@ -485,7 +485,7 @@ class AmpacheShoutCast extends localplay_controller {
* This returns bool/int values for features, loop, repeat and any other features * This returns bool/int values for features, loop, repeat and any other features
* That this localplay method support * That this localplay method support
*/ */
public function status() { public function status() {
return array(); return array();
@ -497,18 +497,18 @@ class AmpacheShoutCast extends localplay_controller {
* a boolean value for the status, to save time this handle * a boolean value for the status, to save time this handle
* is stored in this class * is stored in this class
*/ */
public function connect() { public function connect() {
// We should use this oppertunity to setup the current object // We should use this oppertunity to setup the current object
$info = $this->get_instance(); $info = $this->get_instance();
foreach ($info as $key=>$value) { foreach ($info as $key=>$value) {
$this->$key = $value; $this->$key = $value;
} }
if (!count($info)) { return false; } if (!count($info)) { return false; }
return true; return true;
} // connect } // connect
@ -516,38 +516,38 @@ class AmpacheShoutCast extends localplay_controller {
* get_pid * get_pid
* This returns the pid for the current instance * This returns the pid for the current instance
*/ */
public function get_pid() { public function get_pid() {
// Read and clean! // Read and clean!
$pid = intval(trim(file_get_contents($this->pid))); $pid = intval(trim(file_get_contents($this->pid)));
if (!$pid) { if (!$pid) {
debug_event('Shoutcast','Unable to read PID from ' . $this->pid,'1'); debug_event('Shoutcast','Unable to read PID from ' . $this->pid,'1');
} }
return $pid; return $pid;
} // get_pid } // get_pid
/** /**
* write_playlist * write_playlist
* This takes the files that we've got in our array and writes them out * This takes the files that we've got in our array and writes them out
*/ */
public function write_playlist() { public function write_playlist() {
$string = implode("\n",$this->files) . "\n"; $string = implode("\n",$this->files) . "\n";
$handle = fopen($this->playlist,'w');
if (!is_resource($handle)) { $handle = fopen($this->playlist,'w');
debug_event('Shoutcast','Unable to open ' . $this->playlist . ' for writing playlist file','1');
return false;
}
fwrite($handle,$string); if (!is_resource($handle)) {
fclose($handle); debug_event('Shoutcast','Unable to open ' . $this->playlist . ' for writing playlist file','1');
return false;
return true; }
fwrite($handle,$string);
fclose($handle);
return true;
} // write_playlist } // write_playlist
@ -555,66 +555,66 @@ class AmpacheShoutCast extends localplay_controller {
* get_playlist * get_playlist
* This reads in the playlist and returns an array of filenames * This reads in the playlist and returns an array of filenames
*/ */
public function get_playlist() { public function get_playlist() {
$data = file_get_contents($this->playlist); $data = file_get_contents($this->playlist);
if (!$data) { if (!$data) {
debug_event('Shoutcast','Unable to open ' . $this->playlist . ' for reading or file empty','1'); debug_event('Shoutcast','Unable to open ' . $this->playlist . ' for reading or file empty','1');
return false; return false;
} }
$results = explode("\n",$data); $results = explode("\n",$data);
return $results; return $results;
} // get_playlist } // get_playlist
/** /**
* send_command * send_command
* This is the single funciton that's used to send commands to the * This is the single funciton that's used to send commands to the
* shoutcast server, one function makes it easier to ensure we've escaped our input * shoutcast server, one function makes it easier to ensure we've escaped our input
*/ */
public function send_command($command,$options=array()) { public function send_command($command,$options=array()) {
// Just incase someone uses some crazy syntax // Just incase someone uses some crazy syntax
$command = strtolower($command); $command = strtolower($command);
$pid = $this->get_pid(); $pid = $this->get_pid();
if (!$pid) { return false; } if (!$pid) { return false; }
switch ($command) { switch ($command) {
case 'hup': case 'hup':
$command = '/bin/kill -l HUP ' . escapeshellarg($pid); $command = '/bin/kill -l HUP ' . escapeshellarg($pid);
system($command,$return); system($command,$return);
break; break;
case 'reload': case 'reload':
$command = '/bin/kill -l USR1 ' . escapeshellarg($pid); $command = '/bin/kill -l USR1 ' . escapeshellarg($pid);
system($command,$return); system($command,$return);
break; break;
case 'next': case 'next':
$commend = '/bin/kill -l WINCH ' . escapeshellarg($pid); $commend = '/bin/kill -l WINCH ' . escapeshellarg($pid);
system($command,$return); system($command,$return);
break; break;
case 'shuffle': case 'shuffle':
$command = '/bin/kill -l USR2 ' . escapeshellarg($pid); $command = '/bin/kill -l USR2 ' . escapeshellarg($pid);
system($command,$return); system($command,$return);
break; break;
case 'stop': case 'stop':
$command = '/bin/kill -l TERM ' . escapeshellarg($pid); $command = '/bin/kill -l TERM ' . escapeshellarg($pid);
system($command,$return); system($command,$return);
break; break;
case 'start': case 'start':
$command = ''; $command = '';
system($command,$return); system($command,$return);
break; break;
default: default:
return false; return false;
break; break;
} // end switch on the commands we allow } // end switch on the commands we allow
debug_event('Shoutcat','Issued ' . $command . ' and received ' . $return,'3');
return false; debug_event('Shoutcat','Issued ' . $command . ' and received ' . $return,'3');
return false;
} // send_command } // send_command