1
0
Fork 0
mirror of https://github.com/Yetangitu/ampache synced 2025-10-03 09:49:30 +02:00

Ampache code now respect PSR-2 code style

This commit is contained in:
Afterster 2013-11-17 18:54:14 +01:00
parent 607318cb59
commit 22cb316a48
254 changed files with 4022 additions and 4063 deletions

View file

@ -56,7 +56,7 @@ switch ($_REQUEST['action']) {
Access::create($_POST); Access::create($_POST);
// Create Additional stuff based on the type // Create Additional stuff based on the type
if ($_POST['addtype'] == 'stream' || if ($_POST['addtype'] == 'stream' ||
$_POST['addtype'] == 'all' $_POST['addtype'] == 'all'
) { ) {
$_POST['type'] = 'stream'; $_POST['type'] = 'stream';
@ -70,8 +70,7 @@ switch ($_REQUEST['action']) {
if (!Error::occurred()) { if (!Error::occurred()) {
$url = Config::get('web_path') . '/admin/access.php'; $url = Config::get('web_path') . '/admin/access.php';
show_confirmation(T_('Added'), T_('Your new Access Control List(s) have been created'),$url); show_confirmation(T_('Added'), T_('Your new Access Control List(s) have been created'),$url);
} } else {
else {
$action = 'show_add_' . $_POST['type']; $action = 'show_add_' . $_POST['type'];
require_once Config::get('prefix') . '/templates/show_add_access.inc.php'; require_once Config::get('prefix') . '/templates/show_add_access.inc.php';
} }
@ -85,8 +84,7 @@ switch ($_REQUEST['action']) {
$access->update($_POST); $access->update($_POST);
if (!Error::occurred()) { if (!Error::occurred()) {
show_confirmation(T_('Updated'), T_('Access List Entry updated'), Config::get('web_path').'/admin/access.php'); show_confirmation(T_('Updated'), T_('Access List Entry updated'), Config::get('web_path').'/admin/access.php');
} } else {
else {
$access->format(); $access->format();
require_once Config::get('prefix') . '/templates/show_edit_access.inc.php'; require_once Config::get('prefix') . '/templates/show_edit_access.inc.php';
} }
@ -110,4 +108,3 @@ switch ($_REQUEST['action']) {
break; break;
} // end switch on action } // end switch on action
UI::show_footer(); UI::show_footer();
?>

View file

@ -44,7 +44,7 @@ switch ($_REQUEST['action']) {
toggle_visible('ajax-loading'); toggle_visible('ajax-loading');
ob_end_flush(); ob_end_flush();
if (Config::get('demo_mode')) { break; } if (Config::get('demo_mode')) { break; }
if ($_REQUEST['catalogs'] ) { if ($_REQUEST['catalogs']) {
foreach ($_REQUEST['catalogs'] as $catalog_id) { foreach ($_REQUEST['catalogs'] as $catalog_id) {
$catalog = Catalog::create_from_id($catalog_id); $catalog = Catalog::create_from_id($catalog_id);
$catalog->add_to_catalog($_POST); $catalog->add_to_catalog($_POST);
@ -130,8 +130,7 @@ switch ($_REQUEST['action']) {
if (count($song)) { if (count($song)) {
$catalog->remove_songs($song); $catalog->remove_songs($song);
$body = T_ngettext('Song Removed', 'Songs Removed', count($song)); $body = T_ngettext('Song Removed', 'Songs Removed', count($song));
} } else {
else {
$body = T_('No Songs Removed'); $body = T_('No Songs Removed');
} }
$url = Config::get('web_path') . '/admin/catalog.php'; $url = Config::get('web_path') . '/admin/catalog.php';
@ -148,7 +147,7 @@ switch ($_REQUEST['action']) {
// Make sure they checked something // Make sure they checked something
if (isset($_REQUEST['catalogs'])) { if (isset($_REQUEST['catalogs'])) {
foreach($_REQUEST['catalogs'] as $catalog_id) { foreach ($_REQUEST['catalogs'] as $catalog_id) {
$catalog = Catalog::create_from_id($catalog_id); $catalog = Catalog::create_from_id($catalog_id);
$catalog->clean_catalog(); $catalog->clean_catalog();
} // end foreach catalogs } // end foreach catalogs
@ -199,7 +198,7 @@ switch ($_REQUEST['action']) {
if (Config::get('demo_mode')) { break; } if (Config::get('demo_mode')) { break; }
ob_end_flush(); ob_end_flush();
if (!strlen($_POST['type']) || $_POST['type'] == 'none') { if (!strlen($_POST['type']) || $_POST['type'] == 'none') {
Error::add('general', T_('Error: Please select a catalog type')); Error::add('general', T_('Error: Please select a catalog type'));
} }
@ -236,8 +235,7 @@ switch ($_REQUEST['action']) {
show_confirmation('','', Config::get('web_path').'/admin/catalog.php'); show_confirmation('','', Config::get('web_path').'/admin/catalog.php');
} } else {
else {
require Config::get('prefix') . '/templates/show_add_catalog.inc.php'; require Config::get('prefix') . '/templates/show_add_catalog.inc.php';
} }
break; break;
@ -268,8 +266,7 @@ switch ($_REQUEST['action']) {
$songs = Song::get_disabled(); $songs = Song::get_disabled();
if (count($songs)) { if (count($songs)) {
require Config::get('prefix') . '/templates/show_disabled_songs.inc.php'; require Config::get('prefix') . '/templates/show_disabled_songs.inc.php';
} } else {
else {
echo "<div class=\"error\" align=\"center\">" . T_('No Disabled songs found') . "</div>"; echo "<div class=\"error\" align=\"center\">" . T_('No Disabled songs found') . "</div>";
} }
break; break;
@ -308,5 +305,3 @@ switch ($_REQUEST['action']) {
/* Show the Footer */ /* Show the Footer */
UI::show_footer(); UI::show_footer();
?>

View file

@ -43,4 +43,3 @@ switch ($_REQUEST['action']) {
} // end switch on action } // end switch on action
UI::show_footer(); UI::show_footer();
?>

View file

@ -51,7 +51,7 @@ switch ($_REQUEST['action']) {
$date = date("d/m/Y",time()); $date = date("d/m/Y",time());
switch($_REQUEST['export_format']) { switch ($_REQUEST['export_format']) {
case 'itunes': case 'itunes':
header("Content-Type: application/itunes+xml; charset=utf-8"); header("Content-Type: application/itunes+xml; charset=utf-8");
header("Content-Disposition: attachment; filename=\"ampache-itunes-$date.xml\""); header("Content-Disposition: attachment; filename=\"ampache-itunes-$date.xml\"");
@ -74,4 +74,3 @@ switch ($_REQUEST['action']) {
} // end switch on action } // end switch on action
UI::show_footer(); UI::show_footer();
?>

View file

@ -43,15 +43,13 @@ switch ($_REQUEST['action']) {
/* If no change in string take Drop down */ /* If no change in string take Drop down */
if (strcasecmp(stripslashes($_REQUEST['album_string']),$song->get_album_name()) == 0) { if (strcasecmp(stripslashes($_REQUEST['album_string']),$song->get_album_name()) == 0) {
$album = $song->get_album_name($_REQUEST['album']); $album = $song->get_album_name($_REQUEST['album']);
} } else {
else {
$album = scrub_in($_REQUEST['album_string']); $album = scrub_in($_REQUEST['album_string']);
} }
if (strcasecmp(stripslashes($_REQUEST['artist_string']),$song->get_artist_name()) == 0) { if (strcasecmp(stripslashes($_REQUEST['artist_string']),$song->get_artist_name()) == 0) {
$artist = $song->get_artist_name($_REQUEST['artist']); $artist = $song->get_artist_name($_REQUEST['artist']);
} } else {
else {
$artist = scrub_in($_REQUEST['artist_string']); $artist = scrub_in($_REQUEST['artist_string']);
} }
@ -235,8 +233,7 @@ switch ($_REQUEST['action']) {
$flag = new Flag($flag_id); $flag = new Flag($flag_id);
if ($_REQUEST['update_action'] == 'reject') { if ($_REQUEST['update_action'] == 'reject') {
$flag->delete_flag(); $flag->delete_flag();
} } else {
else {
$flag->approve(); $flag->approve();
} }
} // end foreach flags } // end foreach flags
@ -253,8 +250,7 @@ switch ($_REQUEST['action']) {
case 'disable': case 'disable':
$song_obj = new Song(); $song_obj = new Song();
// If we pass just one, make it still work // If we pass just one, make it still work
if (!is_array($_REQUEST['song_ids'])) { $song_obj->update_enabled(0,$_REQUEST['song_ids']); } if (!is_array($_REQUEST['song_ids'])) { $song_obj->update_enabled(0,$_REQUEST['song_ids']); } else {
else {
foreach ($_REQUEST['song_ids'] as $song_id) { foreach ($_REQUEST['song_ids'] as $song_id) {
$song_obj->update_enabled(0,$song_id); $song_obj->update_enabled(0,$song_id);
} // end foreach } // end foreach
@ -264,8 +260,7 @@ switch ($_REQUEST['action']) {
case 'enabled': case 'enabled':
$song_obj = new Song(); $song_obj = new Song();
// If we pass just one, make it still work // If we pass just one, make it still work
if (!is_array($_REQUEST['song_ids'])) { $song_obj->update_enabled(1,$_REQUEST['song_ids']); } if (!is_array($_REQUEST['song_ids'])) { $song_obj->update_enabled(1,$_REQUEST['song_ids']); } else {
else {
foreach ($_REQUEST['song_ids'] as $song_id) { foreach ($_REQUEST['song_ids'] as $song_id) {
$song_obj->update_enabled(1,$song_id); $song_obj->update_enabled(1,$song_id);
} // end foreach } // end foreach
@ -295,4 +290,3 @@ switch ($_REQUEST['action']) {
} // end switch } // end switch
UI::show_footer(); UI::show_footer();
?>

View file

@ -43,4 +43,3 @@ switch ($_REQUEST['action']) {
} }
UI::show_footer(); UI::show_footer();
?>

View file

@ -38,7 +38,7 @@ switch ($_REQUEST['action']) {
} }
// Multi-byte Character Mail // Multi-byte Character Mail
if(function_exists('mb_language')) { if (function_exists('mb_language')) {
ini_set("mbstring.internal_encoding","UTF-8"); ini_set("mbstring.internal_encoding","UTF-8");
mb_language("uni"); mb_language("uni");
} }
@ -51,17 +51,15 @@ switch ($_REQUEST['action']) {
if ($_REQUEST['from'] == 'system') { if ($_REQUEST['from'] == 'system') {
$mailer->set_default_sender(); $mailer->set_default_sender();
} } else {
else {
$mailer->sender = $GLOBALS['user']->email; $mailer->sender = $GLOBALS['user']->email;
$mailer->sender_name = $GLOBALS['user']->fullname; $mailer->sender_name = $GLOBALS['user']->fullname;
} }
if($mailer->send_to_group($_REQUEST['to'])) { if ($mailer->send_to_group($_REQUEST['to'])) {
$title = T_('E-mail Sent'); $title = T_('E-mail Sent');
$body = T_('Your E-mail was successfully sent.'); $body = T_('Your E-mail was successfully sent.');
} } else {
else {
$title = T_('E-mail Not Sent'); $title = T_('E-mail Not Sent');
$body = T_('Your E-mail was not sent.'); $body = T_('Your E-mail was not sent.');
} }
@ -75,6 +73,3 @@ switch ($_REQUEST['action']) {
} // end switch } // end switch
UI::show_footer(); UI::show_footer();
?>

View file

@ -60,7 +60,7 @@ switch ($_REQUEST['action']) {
} }
$catalog->install(); $catalog->install();
/* Show Confirmation */ /* Show Confirmation */
$url = Config::get('web_path') . '/admin/modules.php?action=show_catalog_types'; $url = Config::get('web_path') . '/admin/modules.php?action=show_catalog_types';
$title = T_('Plugin Installed'); $title = T_('Plugin Installed');
@ -201,5 +201,3 @@ switch ($_REQUEST['action']) {
} // end switch } // end switch
UI::show_footer(); UI::show_footer();
?>

View file

@ -59,4 +59,3 @@ switch ($_REQUEST['action']) {
} // end switch on action } // end switch on action
UI::show_footer(); UI::show_footer();
?>

View file

@ -57,5 +57,3 @@ switch ($_REQUEST['action']) {
} // end switch } // end switch
UI::show_footer(); UI::show_footer();
?>

View file

@ -123,9 +123,7 @@ switch ($_REQUEST['action']) {
$_REQUEST['action'] = 'show_add_user'; $_REQUEST['action'] = 'show_add_user';
break; break;
} }
if ($access == 5){ $access = T_('Guest');} if ($access == 5) { $access = T_('Guest');} elseif ($access == 25) { $access = T_('User');} elseif ($access == 100) { $access = T_('Admin');}
elseif ($access == 25){ $access = T_('User');}
elseif ($access == 100){ $access = T_('Admin');}
/* HINT: %1 Username, %2 Access num */ /* HINT: %1 Username, %2 Access num */
show_confirmation(T_('New User Added'),sprintf(T_('%1$s has been created with an access level of %2$s'), $username, $access), Config::get('web_path').'/admin/users.php'); show_confirmation(T_('New User Added'),sprintf(T_('%1$s has been created with an access level of %2$s'), $username, $access), Config::get('web_path').'/admin/users.php');
@ -139,8 +137,7 @@ switch ($_REQUEST['action']) {
$client = new User($_REQUEST['user_id']); $client = new User($_REQUEST['user_id']);
if ($client->disable()) { if ($client->disable()) {
show_confirmation(T_('User Disabled'),$client->fullname . ' (' . $client->username . ')', Config::get('web_path'). '/admin/users.php'); show_confirmation(T_('User Disabled'),$client->fullname . ' (' . $client->username . ')', Config::get('web_path'). '/admin/users.php');
} } else {
else {
show_confirmation(T_('Error'), T_('Unable to Disabled last Administrator'), Config::get('web_path').'/admin/users.php'); show_confirmation(T_('Error'), T_('Unable to Disabled last Administrator'), Config::get('web_path').'/admin/users.php');
} }
break; break;
@ -158,8 +155,7 @@ switch ($_REQUEST['action']) {
$client = new User($_REQUEST['user_id']); $client = new User($_REQUEST['user_id']);
if ($client->delete()) { if ($client->delete()) {
show_confirmation(T_('User Deleted'), sprintf(T_('%s has been Deleted'), $client->username), Config::get('web_path'). "/admin/users.php"); show_confirmation(T_('User Deleted'), sprintf(T_('%s has been Deleted'), $client->username), Config::get('web_path'). "/admin/users.php");
} } else {
else {
show_confirmation(T_('Delete Error'), T_("Unable to delete last Admin User"), Config::get('web_path')."/admin/users.php"); show_confirmation(T_('Delete Error'), T_("Unable to delete last Admin User"), Config::get('web_path')."/admin/users.php");
} }
break; break;
@ -175,10 +171,9 @@ switch ($_REQUEST['action']) {
/* get the user and their history */ /* get the user and their history */
$working_user = new User($_REQUEST['user_id']); $working_user = new User($_REQUEST['user_id']);
if (!isset($_REQUEST['all'])){ if (!isset($_REQUEST['all'])) {
$history = $working_user->get_ip_history(0,1); $history = $working_user->get_ip_history(0,1);
} } else {
else {
$history = $working_user->get_ip_history(); $history = $working_user->get_ip_history();
} }
require Config::get('prefix') . '/templates/show_ip_history.inc.php'; require Config::get('prefix') . '/templates/show_ip_history.inc.php';
@ -206,5 +201,3 @@ switch ($_REQUEST['action']) {
/* Show the footer */ /* Show the footer */
UI::show_footer(); UI::show_footer();
?>

View file

@ -28,7 +28,7 @@ require_once Config::get('prefix') . '/templates/header.inc.php';
switch ($_REQUEST['action']) { switch ($_REQUEST['action']) {
case 'clear_art': case 'clear_art':
if (!$GLOBALS['user']->has_access('75')) { UI::access_denied(); } if (!$GLOBALS['user']->has_access('75')) { UI::access_denied(); }
$art = new Art($_GET['album_id'],'album'); $art = new Art($_GET['album_id'],'album');
$art->reset(); $art->reset();
show_confirmation(T_('Album Art Cleared'), T_('Album Art information has been removed from the database'),"/albums.php?action=show&amp;album=" . $art->uid); show_confirmation(T_('Album Art Cleared'), T_('Album Art information has been removed from the database'),"/albums.php?action=show&amp;album=" . $art->uid);
break; break;
@ -48,7 +48,7 @@ switch ($_REQUEST['action']) {
// If we got something back insert it // If we got something back insert it
if ($image_data) { if ($image_data) {
$art = new Art($album->id,'album'); $art = new Art($album->id,'album');
$art->insert($image_data,$_FILES['file']['type']); $art->insert($image_data,$_FILES['file']['type']);
show_confirmation(T_('Album Art Inserted'),'',"/albums.php?action=show&amp;album=" . $album->id); show_confirmation(T_('Album Art Inserted'),'',"/albums.php?action=show&amp;album=" . $album->id);
} }
@ -65,7 +65,7 @@ switch ($_REQUEST['action']) {
// get the Album information // get the Album information
$album = new Album($_GET['album_id']); $album = new Album($_GET['album_id']);
$album->format(); $album->format();
$art = new Art($album->id,'album'); $art = new Art($album->id,'album');
$images = array(); $images = array();
$cover_url = array(); $cover_url = array();
@ -88,14 +88,12 @@ switch ($_REQUEST['action']) {
// Build the options for our search // Build the options for our search
if (isset($_REQUEST['artist_name'])) { if (isset($_REQUEST['artist_name'])) {
$artist = scrub_in($_REQUEST['artist_name']); $artist = scrub_in($_REQUEST['artist_name']);
} } elseif ($album->artist_count == '1') {
elseif ($album->artist_count == '1') {
$artist = $album->f_artist_name; $artist = $album->f_artist_name;
} }
if (isset($_REQUEST['album_name'])) { if (isset($_REQUEST['album_name'])) {
$album_name = scrub_in($_REQUEST['album_name']); $album_name = scrub_in($_REQUEST['album_name']);
} } else {
else {
$album_name = $album->full_name; $album_name = $album->full_name;
} }
@ -145,7 +143,7 @@ switch ($_REQUEST['action']) {
/* Check to see if we have the image url still */ /* Check to see if we have the image url still */
$image_id = $_REQUEST['image']; $image_id = $_REQUEST['image'];
$album_id = $_REQUEST['album_id']; $album_id = $_REQUEST['album_id'];
$art = new Art($album_id,'album'); $art = new Art($album_id,'album');
$image = Art::get_from_source($_SESSION['form']['images'][$image_id], 'album'); $image = Art::get_from_source($_SESSION['form']['images'][$image_id], 'album');
$mime = $_SESSION['form']['images'][$image_id]['mime']; $mime = $_SESSION['form']['images'][$image_id]['mime'];
@ -177,4 +175,3 @@ switch ($_REQUEST['action']) {
} // switch on view } // switch on view
UI::show_footer(); UI::show_footer();
?>

View file

@ -27,7 +27,7 @@ UI::show_header();
/** /**
* Display Switch * Display Switch
*/ */
switch($_REQUEST['action']) { switch ($_REQUEST['action']) {
case 'show': case 'show':
$artist = new Artist($_REQUEST['artist']); $artist = new Artist($_REQUEST['artist']);
$artist->format(); $artist->format();
@ -73,8 +73,7 @@ switch($_REQUEST['action']) {
} else { } else {
$GLOBALS['error']->add_error('general', sprintf(T_('Error: \'%s\' is not a valid ID'), $artist_id)); $GLOBALS['error']->add_error('general', sprintf(T_('Error: \'%s\' is not a valid ID'), $artist_id));
} }
} } else
else
$GLOBALS['error']->add_error('general', sprintf(T_('Error: No such artist \'%s\''), $_REQUEST['artist'])); $GLOBALS['error']->add_error('general', sprintf(T_('Error: No such artist \'%s\''), $_REQUEST['artist']));
} else { } else {
$GLOBALS['error']->add_error('general', T_("Error: Errenous request")); $GLOBALS['error']->add_error('general', T_("Error: Errenous request"));
@ -180,8 +179,7 @@ switch($_REQUEST['action']) {
case 'match': case 'match':
case 'Match': case 'Match':
$match = scrub_in($_REQUEST['match']); $match = scrub_in($_REQUEST['match']);
if ($match == "Browse" || $match == "Show_all") { $chr = ""; } if ($match == "Browse" || $match == "Show_all") { $chr = ""; } else { $chr = $match; }
else { $chr = $match; }
/* Enclose this in the purty box! */ /* Enclose this in the purty box! */
require Config::get('prefix') . '/templates/show_box_top.inc.php'; require Config::get('prefix') . '/templates/show_box_top.inc.php';
show_alphabet_list('artists','artists.php',$match); show_alphabet_list('artists','artists.php',$match);
@ -190,16 +188,13 @@ switch($_REQUEST['action']) {
if ($match === "Browse") { if ($match === "Browse") {
show_artists(); show_artists();
} } elseif ($match === "Show_all") {
elseif ($match === "Show_all") {
$offset_limit = 999999; $offset_limit = 999999;
show_artists(); show_artists();
} } else {
else {
if ($chr == '') { if ($chr == '') {
show_artists('A'); show_artists('A');
} } else {
else {
show_artists($chr); show_artists($chr);
} }
} }
@ -207,4 +202,3 @@ switch($_REQUEST['action']) {
} // end switch } // end switch
UI::show_footer(); UI::show_footer();
?>

View file

@ -45,7 +45,7 @@ switch ($_REQUEST['action']) {
case 'smartplaylist': case 'smartplaylist':
$search = new Search('song', $_REQUEST['id']); $search = new Search('song', $_REQUEST['id']);
$sql = $search->to_sql(); $sql = $search->to_sql();
$sql = $sql['base'] . ' ' . $sql['table_sql'] . ' WHERE ' . $sql = $sql['base'] . ' ' . $sql['table_sql'] . ' WHERE ' .
$sql['where_sql']; $sql['where_sql'];
$db_results = Dba::read($sql); $db_results = Dba::read($sql);
$media_ids = array(); $media_ids = array();
@ -94,4 +94,3 @@ $song_files = get_song_files($media_ids);
set_memory_limit($song_files['1']+32); set_memory_limit($song_files['1']+32);
send_zip($name,$song_files['0']); send_zip($name,$song_files['0']);
exit; exit;
?>

View file

@ -54,7 +54,7 @@ switch ($_REQUEST['action']) {
UI::show_header(); UI::show_header();
switch($_REQUEST['action']) { switch ($_REQUEST['action']) {
case 'file': case 'file':
break; break;
case 'album': case 'album':
@ -119,4 +119,3 @@ $browse->store();
/* Show the Footer */ /* Show the Footer */
UI::show_footer(); UI::show_footer();
?>

View file

@ -77,8 +77,7 @@ switch ($_REQUEST['action']) {
// Create the playlist // Create the playlist
Democratic::create($_POST); Democratic::create($_POST);
$democratic = Democratic::get_current_playlist(); $democratic = Democratic::get_current_playlist();
} } else {
else {
$democratic->update($_POST); $democratic->update($_POST);
} }
@ -123,5 +122,3 @@ switch ($_REQUEST['action']) {
} // end switch on action } // end switch on action
UI::show_footer(); UI::show_footer();
?>

View file

@ -58,4 +58,3 @@ switch ($action) {
} // end action switch } // end action switch
UI::show_footer(); UI::show_footer();
?>

View file

@ -23,5 +23,3 @@
require_once 'lib/init.php'; require_once 'lib/init.php';
require_once Config::get('prefix') . '/templates/show_html5_player.inc.php'; require_once Config::get('prefix') . '/templates/show_html5_player.inc.php';
?>

View file

@ -24,5 +24,3 @@ require_once 'lib/init.php';
$iframed = true; $iframed = true;
require_once Config::get('prefix') . '/templates/show_html5_player.inc.php'; require_once Config::get('prefix') . '/templates/show_html5_player.inc.php';
?>

View file

@ -39,14 +39,14 @@ if (!Session::exists('interface', $_COOKIE[Config::get('session_name')]) && !Ses
} }
// If we aren't resizing just trash thumb // If we aren't resizing just trash thumb
if (!Config::get('resize_images')) { $_GET['thumb'] = null; } if (!Config::get('resize_images')) { $_GET['thumb'] = null; }
// FIXME: Legacy stuff - should be removed after a version or so // FIXME: Legacy stuff - should be removed after a version or so
if (!isset($_GET['object_type'])) { if (!isset($_GET['object_type'])) {
$_GET['object_type'] = 'album'; $_GET['object_type'] = 'album';
} }
$type = Art::validate_type($_GET['object_type']); $type = Art::validate_type($_GET['object_type']);
/* Decide what size this image is */ /* Decide what size this image is */
switch ($_GET['thumb']) { switch ($_GET['thumb']) {
@ -91,23 +91,22 @@ switch ($_GET['type']) {
$media = new $type($_GET['id']); $media = new $type($_GET['id']);
$filename = $media->name; $filename = $media->name;
$art = new Art($media->id,$type); $art = new Art($media->id,$type);
$art->get_db(); $art->get_db();
if (!$art->raw_mime) { if (!$art->raw_mime) {
$mime = 'image/jpeg'; $mime = 'image/jpeg';
$image = file_get_contents(Config::get('prefix') . $image = file_get_contents(Config::get('prefix') .
Config::get('theme_path') . Config::get('theme_path') .
'/images/blankalbum.jpg'); '/images/blankalbum.jpg');
} } else {
else {
if ($_GET['thumb']) { if ($_GET['thumb']) {
$thumb_data = $art->get_thumb($size); $thumb_data = $art->get_thumb($size);
} }
$mime = $thumb_data $mime = $thumb_data
? $thumb_data['thumb_mime'] ? $thumb_data['thumb_mime']
: $art->raw_mime; : $art->raw_mime;
$image = $thumb_data $image = $thumb_data
? $thumb_data['thumb'] ? $thumb_data['thumb']
: $art->raw; : $art->raw;
@ -116,7 +115,7 @@ switch ($_GET['type']) {
} // end switch type } // end switch type
if ($image) { if ($image) {
$extension = Art::extension($mime); $extension = Art::extension($mime);
$filename = scrub_out($filename . '.' . $extension); $filename = scrub_out($filename . '.' . $extension);
// Send the headers and output the image // Send the headers and output the image
@ -124,5 +123,3 @@ if ($image) {
$browser->downloadHeaders($filename, $mime, true); $browser->downloadHeaders($filename, $mime, true);
echo $image; echo $image;
} }
?>

View file

@ -49,5 +49,3 @@ if (Config::get('refresh_limit') > 5) {
require_once Config::get('prefix') . '/templates/show_index.inc.php'; require_once Config::get('prefix') . '/templates/show_index.inc.php';
UI::show_footer(); UI::show_footer();
?>

View file

@ -64,16 +64,14 @@ $charset = $_REQUEST['charset'];
if (!$htmllang) { if (!$htmllang) {
if ($_ENV['LANG']) { if ($_ENV['LANG']) {
$lang = $_ENV['LANG']; $lang = $_ENV['LANG'];
} } else {
else {
$lang = 'en_US'; $lang = 'en_US';
} }
if(strpos($lang, '.')) { if (strpos($lang, '.')) {
$langtmp = explode('.', $lang); $langtmp = explode('.', $lang);
$htmllang = $langtmp[0]; $htmllang = $langtmp[0];
$charset = $langtmp[1]; $charset = $langtmp[1];
} } else {
else {
$htmllang = $lang; $htmllang = $lang;
} }
} }
@ -83,18 +81,18 @@ load_gettext();
header ('Content-Type: text/html; charset=' . Config::get('site_charset')); header ('Content-Type: text/html; charset=' . Config::get('site_charset'));
// Correct potential \ or / in the dirname // Correct potential \ or / in the dirname
$safe_dirname = rtrim(dirname($_SERVER['PHP_SELF']),"/\\"); $safe_dirname = rtrim(dirname($_SERVER['PHP_SELF']),"/\\");
$web_path = $http_type . $_SERVER['HTTP_HOST'] . $safe_dirname; $web_path = $http_type . $_SERVER['HTTP_HOST'] . $safe_dirname;
unset($safe_dirname); unset($safe_dirname);
switch ($_REQUEST['action']) { switch ($_REQUEST['action']) {
case 'create_db': case 'create_db':
if ($_POST['db_user'] == 'create_db_user') { if ($_POST['db_user'] == 'create_db_user') {
$new_user = scrub_in($_POST['db_username']); $new_user = scrub_in($_POST['db_username']);
$new_pass = $_POST['db_password']; $new_pass = $_POST['db_password'];
if (!strlen($new_user) || !strlen($new_pass)) { if (!strlen($new_user) || !strlen($new_pass)) {
Error::add('general', T_('Error: Ampache SQL Username or Password missing')); Error::add('general', T_('Error: Ampache SQL Username or Password missing'));
require_once 'templates/show_install.inc.php'; require_once 'templates/show_install.inc.php';
@ -155,5 +153,3 @@ switch ($_REQUEST['action']) {
require_once 'templates/show_install_lang.inc.php'; require_once 'templates/show_install_lang.inc.php';
break; break;
} // end action switch } // end action switch
?>

View file

@ -27,16 +27,15 @@
* *
* @param array $media_ids Media IDs. * @param array $media_ids Media IDs.
*/ */
function get_song_files($media_ids) { function get_song_files($media_ids)
{
$media_files = array(); $media_files = array();
foreach ($media_ids as $element) { foreach ($media_ids as $element) {
if (is_array($element)) { if (is_array($element)) {
$type = array_shift($element); $type = array_shift($element);
$media = new $type(array_shift($element)); $media = new $type(array_shift($element));
} } else {
else {
$media = new Song($element); $media = new Song($element);
} }
if ($media->enabled) { if ($media->enabled) {
@ -57,8 +56,8 @@ function get_song_files($media_ids) {
* @param string $name name of the zip file to be created * @param string $name name of the zip file to be created
* @param string $song_files array of full paths to songs to zip create w/ call to get_song_files * @param string $song_files array of full paths to songs to zip create w/ call to get_song_files
*/ */
function send_zip( $name, $song_files ) { function send_zip( $name, $song_files )
{
// Check if they want to save it to a file, if so then make sure they've // Check if they want to save it to a file, if so then make sure they've
// got a defined path as well and that it's writable. // got a defined path as well and that it's writable.
if (Config::get('file_zip_download') && Config::get('file_zip_path')) { if (Config::get('file_zip_download') && Config::get('file_zip_path')) {
@ -66,8 +65,7 @@ function send_zip( $name, $song_files ) {
if (!is_writable(Config::get('file_zip_path'))) { if (!is_writable(Config::get('file_zip_path'))) {
$in_memory = '1'; $in_memory = '1';
debug_event('Error','File Zip Path:' . Config::get('file_zip_path') . ' is not writable','1'); debug_event('Error','File Zip Path:' . Config::get('file_zip_path') . ' is not writable','1');
} } else {
else {
$in_memory = '0'; $in_memory = '0';
$basedir = Config::get('file_zip_path'); $basedir = Config::get('file_zip_path');
} }
@ -103,4 +101,3 @@ function send_zip( $name, $song_files ) {
$arc->download_file(); $arc->download_file();
} // send_zip } // send_zip
?>

View file

@ -27,8 +27,8 @@
* access based on IP and maybe something else in the future. * access based on IP and maybe something else in the future.
* *
*/ */
class Access { class Access
{
// Variables from DB // Variables from DB
public $id; public $id;
public $name; public $name;
@ -44,8 +44,8 @@ class Access {
* *
* Takes an ID of the access_id dealie :) * Takes an ID of the access_id dealie :)
*/ */
public function __construct($access_id = '') { public function __construct($access_id = '')
{
if (!$access_id) { return false; } if (!$access_id) { return false; }
/* Assign id for use in get_info() */ /* Assign id for use in get_info() */
@ -64,7 +64,8 @@ class Access {
* *
* Gets the vars for $this out of the database. * Gets the vars for $this out of the database.
*/ */
private function _get_info() { private function _get_info()
{
$sql = 'SELECT * FROM `access_list` WHERE `id` = ?'; $sql = 'SELECT * FROM `access_list` WHERE `id` = ?';
$db_results = Dba::read($sql, array($this->id)); $db_results = Dba::read($sql, array($this->id));
@ -79,7 +80,8 @@ class Access {
* This makes the Access object a nice fuzzy human readable object, spiffy * This makes the Access object a nice fuzzy human readable object, spiffy
* ain't it. * ain't it.
*/ */
public function format() { public function format()
{
$this->f_start = inet_ntop($this->start); $this->f_start = inet_ntop($this->start);
$this->f_end = inet_ntop($this->end); $this->f_end = inet_ntop($this->end);
@ -93,7 +95,8 @@ class Access {
* *
* This outputs an error if the IP range is bad. * This outputs an error if the IP range is bad.
*/ */
private static function _verify_range($startp, $endp) { private static function _verify_range($startp, $endp)
{
$startn = @inet_pton($startp); $startn = @inet_pton($startp);
$endn = @inet_pton($endp); $endn = @inet_pton($endp);
@ -120,7 +123,8 @@ class Access {
* This function takes a named array as a datasource and updates the current * This function takes a named array as a datasource and updates the current
* access list entry. * access list entry.
*/ */
public function update($data) { public function update($data)
{
if (!self::_verify_range($data['start'], $data['end'])) { if (!self::_verify_range($data['start'], $data['end'])) {
return false; return false;
} }
@ -135,7 +139,7 @@ class Access {
$sql = 'UPDATE `access_list` SET `start` = ?, `end` = ?, `level` = ?, ' . $sql = 'UPDATE `access_list` SET `start` = ?, `end` = ?, `level` = ?, ' .
'`user` = ?, `name` = ?, `type` = ?, `enabled` = ? WHERE `id` = ?'; '`user` = ?, `name` = ?, `type` = ?, `enabled` = ? WHERE `id` = ?';
$db_results = Dba::write($sql, $db_results = Dba::write($sql,
array($start, $end, $level, $user, $name, $type, $enabled, $this->id)); array($start, $end, $level, $user, $name, $type, $enabled, $this->id));
return true; return true;
@ -147,7 +151,8 @@ class Access {
* This takes a keyed array of data and trys to insert it as a * This takes a keyed array of data and trys to insert it as a
* new ACL entry * new ACL entry
*/ */
public static function create($data) { public static function create($data)
{
if (!self::_verify_range($data['start'], $data['end'])) { if (!self::_verify_range($data['start'], $data['end'])) {
return false; return false;
} }
@ -181,7 +186,8 @@ class Access {
* This sees if the ACL that we've specified already exists in order to * This sees if the ACL that we've specified already exists in order to
* prevent duplicates. The name is ignored. * prevent duplicates. The name is ignored.
*/ */
public static function exists($data) { public static function exists($data)
{
$start = inet_pton($data['start']); $start = inet_pton($data['start']);
$end = inet_pton($data['end']); $end = inet_pton($data['end']);
$type = self::validate_type($data['type']); $type = self::validate_type($data['type']);
@ -203,7 +209,8 @@ class Access {
* *
* deletes the specified access_list entry * deletes the specified access_list entry
*/ */
public static function delete($id) { public static function delete($id)
{
Dba::write('DELETE FROM `access_list` WHERE `id` = ?', array($id)); Dba::write('DELETE FROM `access_list` WHERE `id` = ?', array($id));
} }
@ -212,7 +219,8 @@ class Access {
* *
* This checks if specific functionality is enabled. * This checks if specific functionality is enabled.
*/ */
public static function check_function($type) { public static function check_function($type)
{
switch ($type) { switch ($type) {
case 'download': case 'download':
return Config::get('download'); return Config::get('download');
@ -238,8 +246,8 @@ class Access {
* This takes a type, ip, user, level and key and then returns whether they * This takes a type, ip, user, level and key and then returns whether they
* are allowed. The IP is passed as a dotted quad. * are allowed. The IP is passed as a dotted quad.
*/ */
public static function check_network($type, $user, $level, $ip=null) { public static function check_network($type, $user, $level, $ip=null)
{
if (!Config::get('access_control')) { if (!Config::get('access_control')) {
switch ($type) { switch ($type) {
case 'interface': case 'interface':
@ -281,8 +289,7 @@ class Access {
if (strlen($user) && $user != '-1') { if (strlen($user) && $user != '-1') {
$sql .= " AND `user` IN(?, '-1')"; $sql .= " AND `user` IN(?, '-1')";
$params[] = $user; $params[] = $user;
} } else {
else {
$sql .= " AND `user` = '-1'"; $sql .= " AND `user` = '-1'";
} }
@ -305,8 +312,8 @@ class Access {
* Everything uses the global 0,5,25,50,75,100 stuff. GLOBALS['user'] is * Everything uses the global 0,5,25,50,75,100 stuff. GLOBALS['user'] is
* always used. * always used.
*/ */
public static function check($type, $level) { public static function check($type, $level)
{
if (Config::get('demo_mode')) { if (Config::get('demo_mode')) {
return true; return true;
} }
@ -323,8 +330,7 @@ class Access {
if (Config::get('localplay_level') >= $level if (Config::get('localplay_level') >= $level
|| $GLOBALS['user']->access >= 100) { || $GLOBALS['user']->access >= 100) {
return true; return true;
} } else {
else {
return false; return false;
} }
break; break;
@ -332,8 +338,7 @@ class Access {
// Check their standard user level // Check their standard user level
if ($GLOBALS['user']->access >= $level) { if ($GLOBALS['user']->access >= $level) {
return true; return true;
} } else {
else {
return false; return false;
} }
break; break;
@ -351,8 +356,9 @@ class Access {
* This validates the specified type; it will always return a valid type, * This validates the specified type; it will always return a valid type,
* even if you pass in an invalid one. * even if you pass in an invalid one.
*/ */
public static function validate_type($type) { public static function validate_type($type)
switch($type) { {
switch ($type) {
case 'rpc': case 'rpc':
case 'interface': case 'interface':
case 'network': case 'network':
@ -368,7 +374,8 @@ class Access {
* get_access_lists * get_access_lists
* returns a full listing of all access rules on this server * returns a full listing of all access rules on this server
*/ */
public static function get_access_lists() { public static function get_access_lists()
{
$sql = 'SELECT `id` FROM `access_list`'; $sql = 'SELECT `id` FROM `access_list`';
$db_results = Dba::read($sql); $db_results = Dba::read($sql);
@ -387,7 +394,8 @@ class Access {
* *
* take the int level and return a named level * take the int level and return a named level
*/ */
public function get_level_name() { public function get_level_name()
{
if ($this->level >= '75') { if ($this->level >= '75') {
return T_('All'); return T_('All');
} }
@ -407,7 +415,8 @@ class Access {
* *
* Return a name for the users covered by this ACL. * Return a name for the users covered by this ACL.
*/ */
public function get_user_name() { public function get_user_name()
{
if ($this->user == '-1') { return T_('All'); } if ($this->user == '-1') { return T_('All'); }
$user = new User($this->user); $user = new User($this->user);
@ -419,7 +428,8 @@ class Access {
* *
* This function returns the pretty name for our current type. * This function returns the pretty name for our current type.
*/ */
public function get_type_name() { public function get_type_name()
{
switch ($this->type) { switch ($this->type) {
case 'rpc': case 'rpc':
return T_('API/RPC'); return T_('API/RPC');
@ -437,4 +447,3 @@ class Access {
} }
} }
} }
?>

View file

@ -24,20 +24,20 @@
* Ajax class * Ajax class
* *
* This class is specifically for setting up/printing out ajax related * This class is specifically for setting up/printing out ajax related
* elements onto a page. It takes care of the observing and all that * elements onto a page. It takes care of the observing and all that
* raz-a-ma-taz. * raz-a-ma-taz.
* *
*/ */
class Ajax { class Ajax
{
private static $include_override; private static $include_override;
/** /**
* constructor * constructor
* This is what is called when the class is loaded * This is what is called when the class is loaded
*/ */
public function __construct() { public function __construct()
{
// Rien a faire // Rien a faire
} // constructor } // constructor
@ -47,14 +47,13 @@ class Ajax {
* This returns a string with the correct and full ajax 'observe' stuff * This returns a string with the correct and full ajax 'observe' stuff
* from prototype * from prototype
*/ */
public static function observe($source,$method,$action,$post='') { public static function observe($source,$method,$action,$post='')
{
$non_quoted = array('document','window'); $non_quoted = array('document','window');
if (in_array($source,$non_quoted)) { if (in_array($source,$non_quoted)) {
$source_txt = $source; $source_txt = $source;
} } else {
else {
$source_txt = "'$source'"; $source_txt = "'$source'";
} }
@ -75,7 +74,8 @@ class Ajax {
* url * url
* This takes a string and makes an URL * This takes a string and makes an URL
*/ */
public static function url($action) { public static function url($action)
{
return Config::get('ajax_url') . $action; return Config::get('ajax_url') . $action;
} }
@ -84,26 +84,24 @@ class Ajax {
* This takes the action, the source and the post (if passed) and * This takes the action, the source and the post (if passed) and
* generates the full ajax link * generates the full ajax link
*/ */
public static function action($action,$source,$post='') { public static function action($action,$source,$post='')
{
$url = self::url($action); $url = self::url($action);
$non_quoted = array('document','window'); $non_quoted = array('document','window');
if (in_array($source,$non_quoted)) { if (in_array($source,$non_quoted)) {
$source_txt = $source; $source_txt = $source;
} } else {
else {
$source_txt = "'$source'"; $source_txt = "'$source'";
} }
if ($post) { if ($post) {
$ajax_string = "ajaxPost('$url','$post',$source_txt)"; $ajax_string = "ajaxPost('$url','$post',$source_txt)";
} } else {
else {
$ajax_string = "ajaxPut('$url',$source_txt)"; $ajax_string = "ajaxPut('$url',$source_txt)";
} }
return $ajax_string; return $ajax_string;
} // action } // action
@ -113,8 +111,8 @@ class Ajax {
* This prints out an img of the specified icon with the specified alt * This prints out an img of the specified icon with the specified alt
* text and then sets up the required ajax for it. * text and then sets up the required ajax for it.
*/ */
public static function button($action,$icon,$alt,$source='',$post='',$class='') { public static function button($action,$icon,$alt,$source='',$post='',$class='')
{
// Get the correct action // Get the correct action
$ajax_string = self::action($action,$source,$post); $ajax_string = self::action($action,$source,$post);
@ -141,8 +139,8 @@ class Ajax {
* This prints out the specified text as a link and sets up the required * This prints out the specified text as a link and sets up the required
* ajax for the link so it works correctly * ajax for the link so it works correctly
*/ */
public static function text($action,$text,$source,$post='',$class='') { public static function text($action,$text,$source,$post='',$class='')
{
// Format the string we wanna use // Format the string we wanna use
$ajax_string = self::action($action,$source,$post); $ajax_string = self::action($action,$source,$post);
@ -164,8 +162,8 @@ class Ajax {
* run * run
* This runs the specified action no questions asked * This runs the specified action no questions asked
*/ */
public static function run($action) { public static function run($action)
{
echo "<script type=\"text/javascript\"><!--\n"; echo "<script type=\"text/javascript\"><!--\n";
echo "$action"; echo "$action";
echo "\n--></script>"; echo "\n--></script>";
@ -177,8 +175,8 @@ class Ajax {
* This sets the including div override, used only one place. Kind of a * This sets the including div override, used only one place. Kind of a
* hack. * hack.
*/ */
public static function set_include_override($value) { public static function set_include_override($value)
{
self::$include_override = make_bool($value); self::$include_override = make_bool($value);
} // set_include_override } // set_include_override
@ -188,8 +186,8 @@ class Ajax {
* This checks to see if we're AJAXin'. If we aren't then it echoes out * This checks to see if we're AJAXin'. If we aren't then it echoes out
* the html needed to start a container that can be replaced by Ajax. * the html needed to start a container that can be replaced by Ajax.
*/ */
public static function start_container($name) { public static function start_container($name)
{
if (defined('AJAX_INCLUDE') && !self::$include_override) { return true; } if (defined('AJAX_INCLUDE') && !self::$include_override) { return true; }
echo '<div id="' . scrub_out($name) . '">'; echo '<div id="' . scrub_out($name) . '">';
@ -200,8 +198,8 @@ class Ajax {
* end_container * end_container
* This ends the container if we're not doing the AJAX thing * This ends the container if we're not doing the AJAX thing
*/ */
public static function end_container() { public static function end_container()
{
if (defined('AJAX_INCLUDE') && !self::$include_override) { return true; } if (defined('AJAX_INCLUDE') && !self::$include_override) { return true; }
echo "</div>"; echo "</div>";
@ -211,4 +209,3 @@ class Ajax {
} // end_container } // end_container
} // end Ajax class } // end Ajax class
?>

View file

@ -28,8 +28,8 @@
* it is related to the album table in the database. * it is related to the album table in the database.
* *
*/ */
class Album extends database_object { class Album extends database_object
{
/* Variables from DB */ /* Variables from DB */
public $id; public $id;
public $name; public $name;
@ -51,8 +51,8 @@ class Album extends database_object {
* pull the album or thumb art by default or * pull the album or thumb art by default or
* get any of the counts. * get any of the counts.
*/ */
public function __construct($id='') { public function __construct($id='')
{
if (!$id) { return false; } if (!$id) { return false; }
/* Get the information from the db */ /* Get the information from the db */
@ -75,8 +75,8 @@ class Album extends database_object {
* This is often used by the metadata class, it fills out an album object from a * This is often used by the metadata class, it fills out an album object from a
* named array, _fake is set to true * named array, _fake is set to true
*/ */
public static function construct_from_array($data) { public static function construct_from_array($data)
{
$album = new Album(0); $album = new Album(0);
foreach ($data as $key=>$value) { foreach ($data as $key=>$value) {
$album->$key = $value; $album->$key = $value;
@ -90,11 +90,12 @@ class Album extends database_object {
} // construct_from_array } // construct_from_array
/** /**
* gc * gc
* *
* Cleans out unused albums * Cleans out unused albums
*/ */
public static function gc() { public static function gc()
{
Dba::write('DELETE FROM `album` USING `album` LEFT JOIN `song` ON `song`.`album` = `album`.`id` WHERE `song`.`id` IS NULL'); Dba::write('DELETE FROM `album` USING `album` LEFT JOIN `song` ON `song`.`album` = `album`.`id` WHERE `song`.`id` IS NULL');
} }
@ -103,8 +104,8 @@ class Album extends database_object {
* This takes an array of object ids and caches all of their information * This takes an array of object ids and caches all of their information
* with a single query * with a single query
*/ */
public static function build_cache($ids,$extra=false) { public static function build_cache($ids,$extra=false)
{
// Nothing to do if they pass us nothing // Nothing to do if they pass us nothing
if (!is_array($ids) OR !count($ids)) { return false; } if (!is_array($ids) OR !count($ids)) { return false; }
@ -152,8 +153,8 @@ class Album extends database_object {
* This pulls the extra information from our tables, this is a 3 table join, which is why we don't normally * This pulls the extra information from our tables, this is a 3 table join, which is why we don't normally
* do it * do it
*/ */
private function _get_extra_info() { private function _get_extra_info()
{
if (parent::is_cached('album_extra',$this->id)) { if (parent::is_cached('album_extra',$this->id)) {
return parent::get_from_cache('album_extra',$this->id); return parent::get_from_cache('album_extra',$this->id);
} }
@ -165,7 +166,7 @@ class Album extends database_object {
"`artist`.`name` AS `artist_name`, " . "`artist`.`name` AS `artist_name`, " .
"`artist`.`prefix` AS `artist_prefix`, " . "`artist`.`prefix` AS `artist_prefix`, " .
"`artist`.`id` AS `artist_id` " . "`artist`.`id` AS `artist_id` " .
"FROM `song` INNER JOIN `artist` " . "FROM `song` INNER JOIN `artist` " .
"ON `artist`.`id`=`song`.`artist` " . "ON `artist`.`id`=`song`.`artist` " .
"WHERE `song`.`album` = ? " . "WHERE `song`.`album` = ? " .
"GROUP BY `song`.`album`"; "GROUP BY `song`.`album`";
@ -177,7 +178,7 @@ class Album extends database_object {
$art->get_db(); $art->get_db();
$results['has_art'] = make_bool($art->raw); $results['has_art'] = make_bool($art->raw);
$results['has_thumb'] = make_bool($art->thumb); $results['has_thumb'] = make_bool($art->thumb);
if (Config::get('show_played_times')) { if (Config::get('show_played_times')) {
$results['object_cnt'] = Stats::get_object_count('album', $this->id); $results['object_cnt'] = Stats::get_object_count('album', $this->id);
} }
@ -195,9 +196,9 @@ class Album extends database_object {
*/ */
public static function check($name, $year = 0, $disk = 0, $mbid = null, public static function check($name, $year = 0, $disk = 0, $mbid = null,
$readonly = false) { $readonly = false) {
if ($mbid == '') $mbid = null; if ($mbid == '') $mbid = null;
$trimmed = Catalog::trim_prefix(trim($name)); $trimmed = Catalog::trim_prefix(trim($name));
$name = $trimmed['string']; $name = $trimmed['string'];
$prefix = $trimmed['prefix']; $prefix = $trimmed['prefix'];
@ -223,8 +224,7 @@ class Album extends database_object {
if ($mbid) { if ($mbid) {
$sql .= '= ? '; $sql .= '= ? ';
$params[] = $mbid; $params[] = $mbid;
} } else {
else {
$sql .= 'IS NULL '; $sql .= 'IS NULL ';
} }
@ -232,8 +232,7 @@ class Album extends database_object {
if ($prefix) { if ($prefix) {
$sql .= '= ?'; $sql .= '= ?';
$params[] = $prefix; $params[] = $prefix;
} } else {
else {
$sql .= 'IS NULL'; $sql .= 'IS NULL';
} }
@ -268,8 +267,8 @@ class Album extends database_object {
* and an optional artist, if artist is passed it only gets * and an optional artist, if artist is passed it only gets
* songs with this album + specified artist * songs with this album + specified artist
*/ */
public function get_songs($limit = 0,$artist='') { public function get_songs($limit = 0,$artist='')
{
$results = array(); $results = array();
$sql = "SELECT `id` FROM `song` WHERE `album` = ? "; $sql = "SELECT `id` FROM `song` WHERE `album` = ? ";
@ -296,8 +295,8 @@ class Album extends database_object {
* has_track * has_track
* This checks to see if this album has a track of the specified title * This checks to see if this album has a track of the specified title
*/ */
public function has_track($title) { public function has_track($title)
{
$sql = "SELECT `id` FROM `song` WHERE `album` = ? AND `title` = ?"; $sql = "SELECT `id` FROM `song` WHERE `album` = ? AND `title` = ?";
$db_results = Dba::read($sql, array($this->id, $title)); $db_results = Dba::read($sql, array($this->id, $title));
@ -313,8 +312,8 @@ class Album extends database_object {
* album information with the base required * album information with the base required
* f_link, f_name * f_link, f_name
*/ */
public function format() { public function format()
{
$web_path = Config::get('web_path'); $web_path = Config::get('web_path');
/* Pull the advanced information */ /* Pull the advanced information */
@ -339,8 +338,7 @@ class Album extends database_object {
$artist = scrub_out(UI::truncate($artist), Config::get('ellipse_threshold_artist')); $artist = scrub_out(UI::truncate($artist), Config::get('ellipse_threshold_artist'));
$this->f_artist_link = "<a href=\"$web_path/artists.php?action=show&amp;artist=" . $this->artist_id . "\" title=\"" . scrub_out($this->artist_name) . "\">" . $artist . "</a>"; $this->f_artist_link = "<a href=\"$web_path/artists.php?action=show&amp;artist=" . $this->artist_id . "\" title=\"" . scrub_out($this->artist_name) . "\">" . $artist . "</a>";
$this->f_artist = $artist; $this->f_artist = $artist;
} } else {
else {
$this->f_artist_link = "<span title=\"$this->artist_count " . T_('Artists') . "\">" . T_('Various') . "</span>"; $this->f_artist_link = "<span title=\"$this->artist_count " . T_('Artists') . "\">" . T_('Various') . "</span>";
$this->f_artist = T_('Various'); $this->f_artist = T_('Various');
$this->f_artist_name = $this->f_artist; $this->f_artist_name = $this->f_artist;
@ -361,8 +359,8 @@ class Album extends database_object {
* get_random_songs * get_random_songs
* gets a random number, and a random assortment of songs from this album * gets a random number, and a random assortment of songs from this album
*/ */
function get_random_songs() { public function get_random_songs()
{
$sql = "SELECT `id` FROM `song` WHERE `album` = ? ORDER BY RAND()"; $sql = "SELECT `id` FROM `song` WHERE `album` = ? ORDER BY RAND()";
$db_results = Dba::read($sql, array($this->id)); $db_results = Dba::read($sql, array($this->id));
@ -379,8 +377,8 @@ class Album extends database_object {
* This function takes a key'd array of data and updates this object * This function takes a key'd array of data and updates this object
* as needed, and then throws down with a flag * as needed, and then throws down with a flag
*/ */
public function update($data) { public function update($data)
{
$year = $data['year']; $year = $data['year'];
$artist = $data['artist']; $artist = $data['artist'];
$name = $data['name']; $name = $data['name'];
@ -432,7 +430,8 @@ class Album extends database_object {
* *
* This returns a number of random albums. * This returns a number of random albums.
*/ */
public static function get_random($count = 1, $with_art = false) { public static function get_random($count = 1, $with_art = false)
{
$results = false; $results = false;
if ($with_art) { if ($with_art) {
@ -440,11 +439,10 @@ class Album extends database_object {
"ON (`image`.`object_type` = 'album' AND " . "ON (`image`.`object_type` = 'album' AND " .
'`image`.`object_id` = `album`.`id`) ' . '`image`.`object_id` = `album`.`id`) ' .
'WHERE `image`.`id` IS NOT NULL '; 'WHERE `image`.`id` IS NOT NULL ';
} } else {
else {
$sql = 'SELECT `id` FROM `album` '; $sql = 'SELECT `id` FROM `album` ';
} }
$sql .= 'ORDER BY RAND() LIMIT ' . intval($count); $sql .= 'ORDER BY RAND() LIMIT ' . intval($count);
$db_results = Dba::read($sql); $db_results = Dba::read($sql);
@ -456,5 +454,3 @@ class Album extends database_object {
} }
} //end of album class } //end of album class
?>

View file

@ -25,8 +25,8 @@
* Ampache_RSS Class * Ampache_RSS Class
* *
*/ */
class Ampache_RSS { class Ampache_RSS
{
private $type; private $type;
public $data; public $data;
@ -34,8 +34,8 @@ class Ampache_RSS {
* Constructor * Constructor
* This takes a flagged.id and then pulls in the information for said flag entry * This takes a flagged.id and then pulls in the information for said flag entry
*/ */
public function __construct($type) { public function __construct($type)
{
$this->type = self::validate_type($type); $this->type = self::validate_type($type);
} // constructor } // constructor
@ -45,8 +45,8 @@ class Ampache_RSS {
* This returns the xmldocument for the current rss type, it calls a sub function that gathers the data * This returns the xmldocument for the current rss type, it calls a sub function that gathers the data
* and then uses the xmlDATA class to build the document * and then uses the xmlDATA class to build the document
*/ */
public function get_xml() { public function get_xml()
{
// Function call name // Function call name
$data_function = 'load_' . $this->type; $data_function = 'load_' . $this->type;
$pub_date_function = 'pubdate_' . $this->type; $pub_date_function = 'pubdate_' . $this->type;
@ -65,8 +65,8 @@ class Ampache_RSS {
* get_title * get_title
* This returns the standardized title for the rss feed based on this->type * This returns the standardized title for the rss feed based on this->type
*/ */
public function get_title() { public function get_title()
{
$titles = array('now_playing' => T_('Now Playing'), $titles = array('now_playing' => T_('Now Playing'),
'recently_played' => T_('Recently Played'), 'recently_played' => T_('Recently Played'),
'latest_album' => T_('Newest Albums'), 'latest_album' => T_('Newest Albums'),
@ -80,8 +80,8 @@ class Ampache_RSS {
* get_description * get_description
* This returns the standardized description for the rss feed based on this->type * This returns the standardized description for the rss feed based on this->type
*/ */
public function get_description() { public function get_description()
{
//FIXME: For now don't do any kind of translating //FIXME: For now don't do any kind of translating
return 'Ampache RSS Feeds'; return 'Ampache RSS Feeds';
@ -91,8 +91,8 @@ class Ampache_RSS {
* validate_type * validate_type
* this returns a valid type for an rss feed, if the specified type is invalid it returns a default value * this returns a valid type for an rss feed, if the specified type is invalid it returns a default value
*/ */
public static function validate_type($type) { public static function validate_type($type)
{
$valid_types = array('now_playing','recently_played','latest_album','latest_artist','latest_song', $valid_types = array('now_playing','recently_played','latest_album','latest_artist','latest_song',
'popular_song','popular_album','popular_artist'); 'popular_song','popular_album','popular_artist');
@ -108,8 +108,8 @@ class Ampache_RSS {
* get_display * get_display
* This dumps out some html and an icon for the type of rss that we specify * This dumps out some html and an icon for the type of rss that we specify
*/ */
public static function get_display($type='now_playing') { public static function get_display($type='now_playing')
{
// Default to now playing // Default to now playing
$type = self::validate_type($type); $type = self::validate_type($type);
@ -126,8 +126,8 @@ class Ampache_RSS {
* This loads in the now playing information. This is just the raw data with key=>value pairs that could be turned * This loads in the now playing information. This is just the raw data with key=>value pairs that could be turned
* into an xml document if we so wished * into an xml document if we so wished
*/ */
public static function load_now_playing() { public static function load_now_playing()
{
$data = Stream::get_now_playing(); $data = Stream::get_now_playing();
$results = array(); $results = array();
@ -142,7 +142,7 @@ class Ampache_RSS {
$client = $element['user']; $client = $element['user'];
$title = $format; $title = $format;
$description = $format; $description = $format;
foreach($string_map as $search => $replace) { foreach ($string_map as $search => $replace) {
$trep = 'f_' . $replace; $trep = 'f_' . $replace;
$drep = 'f_' . $replace . '_full'; $drep = 'f_' . $replace . '_full';
$title = str_replace($search, $song->$trep, $title); $title = str_replace($search, $song->$trep, $title);
@ -167,8 +167,8 @@ class Ampache_RSS {
* this is the pub date we should use for the now playing information, * this is the pub date we should use for the now playing information,
* this is a little specific as it uses the 'newest' expire we can find * this is a little specific as it uses the 'newest' expire we can find
*/ */
public static function pubdate_now_playing() { public static function pubdate_now_playing()
{
// Little redundent, should be fixed by an improvement in the get_now_playing stuff // Little redundent, should be fixed by an improvement in the get_now_playing stuff
$data = Stream::get_now_playing(); $data = Stream::get_now_playing();
@ -182,8 +182,8 @@ class Ampache_RSS {
* load_recently_played * load_recently_played
* This loads in the recently played information and formats it up real nice like * This loads in the recently played information and formats it up real nice like
*/ */
public static function load_recently_played() { public static function load_recently_played()
{
//FIXME: The time stuff should be centralized, it's currently in two places, lame //FIXME: The time stuff should be centralized, it's currently in two places, lame
$time_unit = array('', T_('seconds ago'), T_('minutes ago'), T_('hours ago'), T_('days ago'), T_('weeks ago'), T_('months ago'), T_('years ago')); $time_unit = array('', T_('seconds ago'), T_('minutes ago'), T_('hours ago'), T_('days ago'), T_('weeks ago'), T_('months ago'), T_('years ago'));
@ -240,8 +240,8 @@ class Ampache_RSS {
* pubdate_recently_played * pubdate_recently_played
* This just returns the 'newest' recently played entry * This just returns the 'newest' recently played entry
*/ */
public static function pubdate_recently_played() { public static function pubdate_recently_played()
{
$data = Song::get_recently_played(); $data = Song::get_recently_played();
$element = array_shift($data); $element = array_shift($data);

View file

@ -28,8 +28,8 @@
* integrate with Ampache. * integrate with Ampache.
* *
*/ */
class Api { class Api
{
public static $version = '350001'; public static $version = '350001';
private static $browse = null; private static $browse = null;
@ -38,8 +38,8 @@ class Api {
* constructor * constructor
* This really isn't anything to do here, so it's private * This really isn't anything to do here, so it's private
*/ */
private function __construct() { private function __construct()
{
// Rien a faire // Rien a faire
} // constructor } // constructor
@ -48,7 +48,8 @@ class Api {
* _auto_init * _auto_init
* Automatically called when this class is loaded. * Automatically called when this class is loaded.
*/ */
public static function _auto_init() { public static function _auto_init()
{
if (is_null(self::$browse)) { if (is_null(self::$browse)) {
self::$browse = new Browse(null, false); self::$browse = new Browse(null, false);
} }
@ -57,12 +58,12 @@ class Api {
/** /**
* set_filter * set_filter
* This is a play on the browse function, it's different as we expose * This is a play on the browse function, it's different as we expose
* the filters in a slightly different and vastly simpler way to the * the filters in a slightly different and vastly simpler way to the
* end users--so we have to do a little extra work to make them work * end users--so we have to do a little extra work to make them work
* internally. * internally.
*/ */
public static function set_filter($filter,$value) { public static function set_filter($filter,$value)
{
if (!strlen($value)) { return false; } if (!strlen($value)) { return false; }
switch ($filter) { switch ($filter) {
@ -72,8 +73,7 @@ class Api {
$elements = explode('/',$value); $elements = explode('/',$value);
self::$browse->set_filter('add_lt',strtotime($elements['1'])); self::$browse->set_filter('add_lt',strtotime($elements['1']));
self::$browse->set_filter('add_gt',strtotime($elements['0'])); self::$browse->set_filter('add_gt',strtotime($elements['0']));
} } else {
else {
self::$browse->set_filter('add_gt',strtotime($value)); self::$browse->set_filter('add_gt',strtotime($value));
} }
break; break;
@ -83,8 +83,7 @@ class Api {
$elements = explode('/',$value); $elements = explode('/',$value);
self::$browse->set_filter('update_lt',strtotime($elements['1'])); self::$browse->set_filter('update_lt',strtotime($elements['1']));
self::$browse->set_filter('update_gt',strtotime($elements['0'])); self::$browse->set_filter('update_gt',strtotime($elements['0']));
} } else {
else {
self::$browse->set_filter('update_gt',strtotime($value)); self::$browse->set_filter('update_gt',strtotime($value));
} }
break; break;
@ -109,8 +108,8 @@ class Api {
* This is the function that handles verifying a new handshake * This is the function that handles verifying a new handshake
* Takes a timestamp, auth key, and username. * Takes a timestamp, auth key, and username.
*/ */
public static function handshake($input) { public static function handshake($input)
{
$timestamp = preg_replace('/[^0-9]/', '', $input['timestamp']); $timestamp = preg_replace('/[^0-9]/', '', $input['timestamp']);
$passphrase = $input['auth']; $passphrase = $input['auth'];
$ip = $_SERVER['REMOTE_ADDR']; $ip = $_SERVER['REMOTE_ADDR'];
@ -127,7 +126,7 @@ class Api {
} }
// If the timestamp isn't within 30 minutes sucks to be them // If the timestamp isn't within 30 minutes sucks to be them
if (($timestamp < (time() - 1800)) || if (($timestamp < (time() - 1800)) ||
($timestamp > (time() + 1800))) { ($timestamp > (time() + 1800))) {
debug_event('API', 'Login Failed: timestamp out of range', 1); debug_event('API', 'Login Failed: timestamp out of range', 1);
Error::add('api', T_('Login Failed: timestamp out of range')); Error::add('api', T_('Login Failed: timestamp out of range'));
@ -138,8 +137,7 @@ class Api {
// FIXME: Does this if/else make sense with the new ACLs? // FIXME: Does this if/else make sense with the new ACLs?
if (!trim($username)) { if (!trim($username)) {
$user_id = '-1'; $user_id = '-1';
} } else {
else {
$client = User::get_from_username($username); $client = User::get_from_username($username);
$user_id = $client->id; $user_id = $client->id;
} }
@ -196,9 +194,9 @@ class Api {
$db_results = Dba::read($sql); $db_results = Dba::read($sql);
$playlist = Dba::fetch_assoc($db_results); $playlist = Dba::fetch_assoc($db_results);
$sql = "SELECT COUNT(`id`) AS `catalog` FROM `catalog` WHERE `catalog_type`='local'"; $sql = "SELECT COUNT(`id`) AS `catalog` FROM `catalog` WHERE `catalog_type`='local'";
$db_results = Dba::read($sql); $db_results = Dba::read($sql);
$catalog = Dba::fetch_assoc($db_results); $catalog = Dba::fetch_assoc($db_results);
echo XML_Data::keyed_array(array('auth'=>$token, echo XML_Data::keyed_array(array('auth'=>$token,
'api'=>self::$version, 'api'=>self::$version,
@ -211,7 +209,7 @@ class Api {
'artists'=>$counts['artist'], 'artists'=>$counts['artist'],
'playlists'=>$playlist['playlist'], 'playlists'=>$playlist['playlist'],
'videos'=>$vcounts['video'], 'videos'=>$vcounts['video'],
'catalogs'=>$catalog['catalog'])); 'catalogs'=>$catalog['catalog']));
return true; return true;
} // match } // match
@ -227,8 +225,8 @@ class Api {
* This can be called without being authenticated, it is useful for determining if what the status * This can be called without being authenticated, it is useful for determining if what the status
* of the server is, and what version it is running/compatible with * of the server is, and what version it is running/compatible with
*/ */
public static function ping($input) { public static function ping($input)
{
$xmldata = array('server'=>Config::get('version'),'version'=>Api::$version,'compatible'=>'350001'); $xmldata = array('server'=>Config::get('version'),'version'=>Api::$version,'compatible'=>'350001');
// Check and see if we should extend the api sessions (done if valid sess is passed) // Check and see if we should extend the api sessions (done if valid sess is passed)
@ -250,8 +248,8 @@ class Api {
* artist objects. This function is deprecated! * artist objects. This function is deprecated!
* //DEPRECATED * //DEPRECATED
*/ */
public static function artists($input) { public static function artists($input)
{
self::$browse->reset_filters(); self::$browse->reset_filters();
self::$browse->set_type('artist'); self::$browse->set_type('artist');
self::$browse->set_sort('name','ASC'); self::$browse->set_sort('name','ASC');
@ -277,8 +275,8 @@ class Api {
* This returns a single artist based on the UID of said artist * This returns a single artist based on the UID of said artist
* //DEPRECATED * //DEPRECATED
*/ */
public static function artist($input) { public static function artist($input)
{
$uid = scrub_in($input['filter']); $uid = scrub_in($input['filter']);
echo XML_Data::artists(array($uid)); echo XML_Data::artists(array($uid));
@ -288,8 +286,8 @@ class Api {
* artist_albums * artist_albums
* This returns the albums of an artist * This returns the albums of an artist
*/ */
public static function artist_albums($input) { public static function artist_albums($input)
{
$artist = new Artist($input['filter']); $artist = new Artist($input['filter']);
$albums = $artist->get_albums(); $albums = $artist->get_albums();
@ -306,8 +304,8 @@ class Api {
* artist_songs * artist_songs
* This returns the songs of the specified artist * This returns the songs of the specified artist
*/ */
public static function artist_songs($input) { public static function artist_songs($input)
{
$artist = new Artist($input['filter']); $artist = new Artist($input['filter']);
$songs = $artist->get_songs(); $songs = $artist->get_songs();
@ -323,8 +321,8 @@ class Api {
* albums * albums
* This returns albums based on the provided search filters * This returns albums based on the provided search filters
*/ */
public static function albums($input) { public static function albums($input)
{
self::$browse->reset_filters(); self::$browse->reset_filters();
self::$browse->set_type('album'); self::$browse->set_type('album');
self::$browse->set_sort('name','ASC'); self::$browse->set_sort('name','ASC');
@ -347,8 +345,8 @@ class Api {
* album * album
* This returns a single album based on the UID provided * This returns a single album based on the UID provided
*/ */
public static function album($input) { public static function album($input)
{
$uid = scrub_in($input['filter']); $uid = scrub_in($input['filter']);
echo XML_Data::albums(array($uid)); echo XML_Data::albums(array($uid));
@ -358,8 +356,8 @@ class Api {
* album_songs * album_songs
* This returns the songs of a specified album * This returns the songs of a specified album
*/ */
public static function album_songs($input) { public static function album_songs($input)
{
$album = new Album($input['filter']); $album = new Album($input['filter']);
$songs = $album->get_songs(); $songs = $album->get_songs();
@ -376,8 +374,8 @@ class Api {
* tags * tags
* This returns the tags based on the specified filter * This returns the tags based on the specified filter
*/ */
public static function tags($input) { public static function tags($input)
{
self::$browse->reset_filters(); self::$browse->reset_filters();
self::$browse->set_type('tag'); self::$browse->set_type('tag');
self::$browse->set_sort('name','ASC'); self::$browse->set_sort('name','ASC');
@ -399,8 +397,8 @@ class Api {
* tag * tag
* This returns a single tag based on UID * This returns a single tag based on UID
*/ */
public static function tag($input) { public static function tag($input)
{
$uid = scrub_in($input['filter']); $uid = scrub_in($input['filter']);
ob_end_clean(); ob_end_clean();
echo XML_Data::tags(array($uid)); echo XML_Data::tags(array($uid));
@ -411,8 +409,8 @@ class Api {
* tag_artists * tag_artists
* This returns the artists associated with the tag in question as defined by the UID * This returns the artists associated with the tag in question as defined by the UID
*/ */
public static function tag_artists($input) { public static function tag_artists($input)
{
$artists = Tag::get_tag_objects('artist',$input['filter']); $artists = Tag::get_tag_objects('artist',$input['filter']);
XML_Data::set_offset($input['offset']); XML_Data::set_offset($input['offset']);
@ -427,8 +425,8 @@ class Api {
* tag_albums * tag_albums
* This returns the albums associated with the tag in question * This returns the albums associated with the tag in question
*/ */
public static function tag_albums($input) { public static function tag_albums($input)
{
$albums = Tag::get_tag_objects('album',$input['filter']); $albums = Tag::get_tag_objects('album',$input['filter']);
XML_Data::set_offset($input['offset']); XML_Data::set_offset($input['offset']);
@ -443,8 +441,8 @@ class Api {
* tag_songs * tag_songs
* returns the songs for this tag * returns the songs for this tag
*/ */
public static function tag_songs($input) { public static function tag_songs($input)
{
$songs = Tag::get_tag_objects('song',$input['filter']); $songs = Tag::get_tag_objects('song',$input['filter']);
XML_Data::set_offset($input['offset']); XML_Data::set_offset($input['offset']);
@ -459,8 +457,8 @@ class Api {
* songs * songs
* Returns songs based on the specified filter * Returns songs based on the specified filter
*/ */
public static function songs($input) { public static function songs($input)
{
self::$browse->reset_filters(); self::$browse->reset_filters();
self::$browse->set_type('song'); self::$browse->set_type('song');
self::$browse->set_sort('title','ASC'); self::$browse->set_sort('title','ASC');
@ -485,8 +483,8 @@ class Api {
* song * song
* returns a single song * returns a single song
*/ */
public static function song($input) { public static function song($input)
{
$uid = scrub_in($input['filter']); $uid = scrub_in($input['filter']);
ob_end_clean(); ob_end_clean();
@ -499,7 +497,8 @@ class Api {
* *
* This takes a url and returns the song object in question * This takes a url and returns the song object in question
*/ */
public static function url_to_song($input) { public static function url_to_song($input)
{
// Don't scrub, the function needs her raw and juicy // Don't scrub, the function needs her raw and juicy
$data = Stream_URL::parse($input['url']); $data = Stream_URL::parse($input['url']);
ob_end_clean(); ob_end_clean();
@ -510,8 +509,8 @@ class Api {
* playlists * playlists
* This returns playlists based on the specified filter * This returns playlists based on the specified filter
*/ */
public static function playlists($input) { public static function playlists($input)
{
self::$browse->reset_filters(); self::$browse->reset_filters();
self::$browse->set_type('playlist'); self::$browse->set_type('playlist');
self::$browse->set_sort('name','ASC'); self::$browse->set_sort('name','ASC');
@ -533,8 +532,8 @@ class Api {
* playlist * playlist
* This returns a single playlist * This returns a single playlist
*/ */
public static function playlist($input) { public static function playlist($input)
{
$uid = scrub_in($input['filter']); $uid = scrub_in($input['filter']);
ob_end_clean(); ob_end_clean();
@ -546,8 +545,8 @@ class Api {
* playlist_songs * playlist_songs
* This returns the songs for a playlist * This returns the songs for a playlist
*/ */
public static function playlist_songs($input) { public static function playlist_songs($input)
{
$playlist = new Playlist($input['filter']); $playlist = new Playlist($input['filter']);
$items = $playlist->get_items(); $items = $playlist->get_items();
@ -568,7 +567,8 @@ class Api {
* search_songs * search_songs
* This searches the songs and returns... songs * This searches the songs and returns... songs
*/ */
public static function search_songs($input) { public static function search_songs($input)
{
$array['type'] = 'song'; $array['type'] = 'song';
$array['rule_1'] = 'anywhere'; $array['rule_1'] = 'anywhere';
$array['rule_1_input'] = $input['filter']; $array['rule_1_input'] = $input['filter'];
@ -589,8 +589,8 @@ class Api {
* videos * videos
* This returns video objects! * This returns video objects!
*/ */
public static function videos($input) { public static function videos($input)
{
self::$browse->reset_filters(); self::$browse->reset_filters();
self::$browse->set_type('video'); self::$browse->set_type('video');
self::$browse->set_sort('title','ASC'); self::$browse->set_sort('title','ASC');
@ -611,8 +611,8 @@ class Api {
* video * video
* This returns a single video * This returns a single video
*/ */
public static function video($input) { public static function video($input)
{
$video_id = scrub_in($input['filter']); $video_id = scrub_in($input['filter']);
echo XML_Data::videos(array($video_id)); echo XML_Data::videos(array($video_id));
@ -624,8 +624,8 @@ class Api {
* localplay * localplay
* This is for controling localplay * This is for controling localplay
*/ */
public static function localplay($input) { public static function localplay($input)
{
// Load their localplay instance // Load their localplay instance
$localplay = new Localplay(Config::get('localplay_controller')); $localplay = new Localplay(Config::get('localplay_controller'));
$localplay->connect(); $localplay->connect();
@ -651,8 +651,8 @@ class Api {
* democratic * democratic
* This is for controlling democratic play * This is for controlling democratic play
*/ */
public static function democratic($input) { public static function democratic($input)
{
// Load up democratic information // Load up democratic information
$democratic = Democratic::get_current_playlist(); $democratic = Democratic::get_current_playlist();
$democratic->set_parent(); $democratic->set_parent();
@ -709,4 +709,3 @@ class Api {
} // democratic } // democratic
} // API class } // API class
?>

View file

@ -27,8 +27,8 @@
* This was initially in the album class, but was pulled out * This was initially in the album class, but was pulled out
* to be more general and potentially apply to albums, artists, movies etc * to be more general and potentially apply to albums, artists, movies etc
*/ */
class Art extends database_object { class Art extends database_object
{
public $type; public $type;
public $uid; // UID of the object not ID because it's not the ART.ID public $uid; // UID of the object not ID because it's not the ART.ID
public $raw; // Raw art data public $raw; // Raw art data
@ -44,8 +44,8 @@ class Art extends database_object {
* Art constructor, takes the UID of the object and the * Art constructor, takes the UID of the object and the
* object type. * object type.
*/ */
public function __construct($uid, $type = 'album') { public function __construct($uid, $type = 'album')
{
$this->type = Art::validate_type($type); $this->type = Art::validate_type($type);
$this->uid = $uid; $this->uid = $uid;
@ -57,15 +57,15 @@ class Art extends database_object {
* browse all at once and storing it in the cache, this can help if the * browse all at once and storing it in the cache, this can help if the
* db connection is the slow point * db connection is the slow point
*/ */
public static function build_cache($object_ids) { public static function build_cache($object_ids)
{
if (!is_array($object_ids) || !count($object_ids)) { return false; } if (!is_array($object_ids) || !count($object_ids)) { return false; }
$uidlist = '(' . implode(',', $object_ids) . ')'; $uidlist = '(' . implode(',', $object_ids) . ')';
$sql = "SELECT `object_type`, `object_id`, `mime`, `size` FROM `image` WHERE `object_id` IN $uidlist"; $sql = "SELECT `object_type`, `object_id`, `mime`, `size` FROM `image` WHERE `object_id` IN $uidlist";
$db_results = Dba::read($sql); $db_results = Dba::read($sql);
while ($row = Dba::fetch_assoc($db_results)) { while ($row = Dba::fetch_assoc($db_results)) {
parent::add_to_cache('art', $row['object_type'] . parent::add_to_cache('art', $row['object_type'] .
$row['object_id'] . $row['size'], $row); $row['object_id'] . $row['size'], $row);
} }
@ -77,7 +77,8 @@ class Art extends database_object {
* _auto_init * _auto_init
* Called on creation of the class * Called on creation of the class
*/ */
public static function _auto_init() { public static function _auto_init()
{
if (!isset($_SESSION['art_enabled'])) { if (!isset($_SESSION['art_enabled'])) {
$_SESSION['art_enabled'] = (Config::get('bandwidth') > 25); $_SESSION['art_enabled'] = (Config::get('bandwidth') > 25);
} }
@ -88,7 +89,8 @@ class Art extends database_object {
* is_enabled * is_enabled
* Checks whether the user currently wants art * Checks whether the user currently wants art
*/ */
public static function is_enabled() { public static function is_enabled()
{
if (self::$enabled) { if (self::$enabled) {
return true; return true;
} }
@ -100,11 +102,11 @@ class Art extends database_object {
* set_enabled * set_enabled
* Changes the value of enabled * Changes the value of enabled
*/ */
public static function set_enabled($value = null) { public static function set_enabled($value = null)
{
if (is_null($value)) { if (is_null($value)) {
self::$enabled = self::$enabled ? false : true; self::$enabled = self::$enabled ? false : true;
} } else {
else {
self::$enabled = make_bool($value); self::$enabled = make_bool($value);
} }
@ -115,8 +117,8 @@ class Art extends database_object {
* validate_type * validate_type
* This validates the type * This validates the type
*/ */
public static function validate_type($type) { public static function validate_type($type)
{
switch ($type) { switch ($type) {
case 'album': case 'album':
case 'artist': case 'artist':
@ -134,8 +136,8 @@ class Art extends database_object {
* extension * extension
* This returns the file extension for the currently loaded art * This returns the file extension for the currently loaded art
*/ */
public static function extension($mime) { public static function extension($mime)
{
$data = explode("/", $mime); $data = explode("/", $mime);
$extension = $data['1']; $extension = $data['1'];
@ -149,7 +151,8 @@ class Art extends database_object {
* test_image * test_image
* Runs some sanity checks on the putative image * Runs some sanity checks on the putative image
*/ */
public static function test_image($source) { public static function test_image($source)
{
if (strlen($source) < 10) { if (strlen($source) < 10) {
debug_event('Art', 'Invalid image passed', 1); debug_event('Art', 'Invalid image passed', 1);
return false; return false;
@ -175,8 +178,8 @@ class Art extends database_object {
* exists, if it doesn't depending on settings it will try * exists, if it doesn't depending on settings it will try
* to create it. * to create it.
*/ */
public function get($raw=false) { public function get($raw=false)
{
// Get the data either way // Get the data either way
if (!$this->get_db()) { if (!$this->get_db()) {
return false; return false;
@ -184,8 +187,7 @@ class Art extends database_object {
if ($raw || !$this->thumb) { if ($raw || !$this->thumb) {
return $this->raw; return $this->raw;
} } else {
else {
return $this->thumb; return $this->thumb;
} }
@ -198,8 +200,8 @@ class Art extends database_object {
* on if we want to resize and if there is not a thumbnail go * on if we want to resize and if there is not a thumbnail go
* ahead and try to resize * ahead and try to resize
*/ */
public function get_db() { public function get_db()
{
$type = Dba::escape($this->type); $type = Dba::escape($this->type);
$id = Dba::escape($this->uid); $id = Dba::escape($this->uid);
@ -210,8 +212,7 @@ class Art extends database_object {
if ($results['size'] == 'original') { if ($results['size'] == 'original') {
$this->raw = $results['image']; $this->raw = $results['image'];
$this->raw_mime = $results['mime']; $this->raw_mime = $results['mime'];
} } else if (Config::get('resize_images') &&
else if (Config::get('resize_images') &&
$results['size'] == '275x275') { $results['size'] == '275x275') {
$this->thumb = $results['image']; $this->thumb = $results['image'];
$this->raw_mime = $results['mime']; $this->raw_mime = $results['mime'];
@ -228,8 +229,7 @@ class Art extends database_object {
$this->save_thumb($data['thumb'], $data['thumb_mime'], '275x275'); $this->save_thumb($data['thumb'], $data['thumb_mime'], '275x275');
$this->thumb = $data['thumb']; $this->thumb = $data['thumb'];
$this->thumb_mime = $data['thumb_mime']; $this->thumb_mime = $data['thumb_mime'];
} } else {
else {
debug_event('Art','Unable to retrieve or generate thumbnail for ' . $type . '::' . $id,1); debug_event('Art','Unable to retrieve or generate thumbnail for ' . $type . '::' . $id,1);
} }
} // if no thumb, but art and we want to resize } // if no thumb, but art and we want to resize
@ -243,8 +243,8 @@ class Art extends database_object {
* This takes the string representation of an image and inserts it into * This takes the string representation of an image and inserts it into
* the database. You must also pass the mime type. * the database. You must also pass the mime type.
*/ */
public function insert($source, $mime) { public function insert($source, $mime)
{
// Disabled in demo mode cause people suck and upload porn // Disabled in demo mode cause people suck and upload porn
if (Config::get('demo_mode')) { return false; } if (Config::get('demo_mode')) { return false; }
@ -277,8 +277,8 @@ class Art extends database_object {
* reset * reset
* This resets the art in the database * This resets the art in the database
*/ */
public function reset() { public function reset()
{
$type = Dba::escape($this->type); $type = Dba::escape($this->type);
$uid = Dba::escape($this->uid); $uid = Dba::escape($this->uid);
@ -291,8 +291,8 @@ class Art extends database_object {
* save_thumb * save_thumb
* This saves the thumbnail that we're passed * This saves the thumbnail that we're passed
*/ */
public function save_thumb($source, $mime, $size) { public function save_thumb($source, $mime, $size)
{
// Quick sanity check // Quick sanity check
if (!self::test_image($source)) { if (!self::test_image($source)) {
debug_event('Art', 'Not inserting thumbnail, invalid data passed', 1); debug_event('Art', 'Not inserting thumbnail, invalid data passed', 1);
@ -318,7 +318,8 @@ class Art extends database_object {
* Returns the specified resized image. If the requested size doesn't * Returns the specified resized image. If the requested size doesn't
* already exist, create and cache it. * already exist, create and cache it.
*/ */
public function get_thumb($size) { public function get_thumb($size)
{
$sizetext = $size['width'] . 'x' . $size['height']; $sizetext = $size['width'] . 'x' . $size['height'];
$sizetext = Dba::escape($sizetext); $sizetext = Dba::escape($sizetext);
$type = Dba::escape($this->type); $type = Dba::escape($this->type);
@ -348,8 +349,8 @@ class Art extends database_object {
* Only works on gif/jpg/png/bmp. Fails if PHP-GD isn't available * Only works on gif/jpg/png/bmp. Fails if PHP-GD isn't available
* or lacks support for the requested image type. * or lacks support for the requested image type.
*/ */
public function generate_thumb($image,$size,$mime) { public function generate_thumb($image,$size,$mime)
{
$data = explode("/",$mime); $data = explode("/",$mime);
$type = strtolower($data['1']); $type = strtolower($data['1']);
@ -442,8 +443,8 @@ class Art extends database_object {
* ['file'] = FILENAME *** OPTIONAL *** * ['file'] = FILENAME *** OPTIONAL ***
* ['raw'] = Actual Image data, already captured * ['raw'] = Actual Image data, already captured
*/ */
public static function get_from_source($data, $type = 'album') { public static function get_from_source($data, $type = 'album')
{
// Already have the data, this often comes from id3tags // Already have the data, this often comes from id3tags
if (isset($data['raw'])) { if (isset($data['raw'])) {
return $data['raw']; return $data['raw'];
@ -464,7 +465,7 @@ class Art extends database_object {
// Check to see if it's a URL // Check to see if it's a URL
if (isset($data['url'])) { if (isset($data['url'])) {
$snoopy = new Snoopy(); $snoopy = new Snoopy();
if(Config::get('proxy_host') AND Config::get('proxy_port')) { if (Config::get('proxy_host') AND Config::get('proxy_port')) {
$snoopy->proxy_user = Config::get('proxy_host'); $snoopy->proxy_user = Config::get('proxy_host');
$snoopy->proxy_port = Config::get('proxy_port'); $snoopy->proxy_port = Config::get('proxy_port');
$snoopy->proxy_user = Config::get('proxy_user'); $snoopy->proxy_user = Config::get('proxy_user');
@ -490,8 +491,7 @@ class Art extends database_object {
if ($id3['format_name'] == "WMA") { if ($id3['format_name'] == "WMA") {
return $id3['asf']['extended_content_description_object']['content_descriptors']['13']['data']; return $id3['asf']['extended_content_description_object']['content_descriptors']['13']['data'];
} } elseif (isset($id3['id3v2']['APIC'])) {
elseif (isset($id3['id3v2']['APIC'])) {
// Foreach in case they have more then one // Foreach in case they have more then one
foreach ($id3['id3v2']['APIC'] as $image) { foreach ($id3['id3v2']['APIC'] as $image) {
return $image['data']; return $image['data'];
@ -507,8 +507,8 @@ class Art extends database_object {
* url * url
* This returns the constructed URL for the art in question * This returns the constructed URL for the art in question
*/ */
public static function url($uid,$type,$sid=false) { public static function url($uid,$type,$sid=false)
{
$sid = $sid ? scrub_out($sid) : scrub_out(session_id()); $sid = $sid ? scrub_out($sid) : scrub_out(session_id());
$type = self::validate_type($type); $type = self::validate_type($type);
@ -533,8 +533,7 @@ class Art extends database_object {
parent::add_to_cache('art', $key . $row['size'], $row); parent::add_to_cache('art', $key . $row['size'], $row);
if ($row['size'] == 'original') { if ($row['size'] == 'original') {
$mime = $row['mime']; $mime = $row['mime'];
} } else if ($row['size'] == '275x275' && Config::get('resize_images')) {
else if ($row['size'] == '275x275' && Config::get('resize_images')) {
$thumb_mime = $row['mime']; $thumb_mime = $row['mime'];
} }
} }
@ -555,7 +554,8 @@ class Art extends database_object {
* gc * gc
* This cleans up art that no longer has a corresponding object * This cleans up art that no longer has a corresponding object
*/ */
public static function gc() { public static function gc()
{
// iterate over our types and delete the images // iterate over our types and delete the images
foreach (array('album', 'artist') as $type) { foreach (array('album', 'artist') as $type) {
$sql = "DELETE FROM `image` USING `image` LEFT JOIN `" . $sql = "DELETE FROM `image` USING `image` LEFT JOIN `" .
@ -570,8 +570,8 @@ class Art extends database_object {
* gather * gather
* This tries to get the art in question * This tries to get the art in question
*/ */
public function gather($options = array(), $limit = false) { public function gather($options = array(), $limit = false)
{
// Define vars // Define vars
$results = array(); $results = array();
@ -595,8 +595,7 @@ class Art extends database_object {
// They don't want art! // They don't want art!
debug_event('Art', 'art_order is empty, skipping art gathering', 3); debug_event('Art', 'art_order is empty, skipping art gathering', 3);
return array(); return array();
} } elseif (!is_array($config)) {
elseif (!is_array($config)) {
$config = array($config); $config = array($config);
} }
@ -629,7 +628,7 @@ class Art extends database_object {
} }
// Add the results we got to the current set // Add the results we got to the current set
$results = array_merge($results, (array)$data); $results = array_merge($results, (array) $data);
if ($limit && count($results) >= $limit) { if ($limit && count($results) >= $limit) {
return array_slice($results, 0, $limit); return array_slice($results, 0, $limit);
@ -655,7 +654,8 @@ class Art extends database_object {
* gather_db * gather_db
* This function retrieves art that's already in the database * This function retrieves art that's already in the database
*/ */
public function gather_db($limit = null) { public function gather_db($limit = null)
{
if ($this->get_db()) { if ($this->get_db()) {
return array('db' => true); return array('db' => true);
} }
@ -667,21 +667,20 @@ class Art extends database_object {
* This function retrieves art based on MusicBrainz' Advanced * This function retrieves art based on MusicBrainz' Advanced
* Relationships * Relationships
*/ */
public function gather_musicbrainz($limit = 5) { public function gather_musicbrainz($limit = 5)
{
$images = array(); $images = array();
$num_found = 0; $num_found = 0;
if ($this->type == 'album') { if ($this->type == 'album') {
$album = new Album($this->uid); $album = new Album($this->uid);
} } else {
else {
return $images; return $images;
} }
if ($album->mbid) { if ($album->mbid) {
debug_event('mbz-gatherart', "Album MBID: " . $album->mbid, '5'); debug_event('mbz-gatherart', "Album MBID: " . $album->mbid, '5');
} } else {
else {
return $images; return $images;
} }
@ -709,7 +708,7 @@ class Art extends database_object {
$url = 'http://' . $base_url . '/images/P/' . $asin . '.' . $server_num . '.LZZZZZZZ.jpg'; $url = 'http://' . $base_url . '/images/P/' . $asin . '.' . $server_num . '.LZZZZZZZ.jpg';
debug_event('mbz-gatherart', "Evaluating Amazon URL: " . $url, '5'); debug_event('mbz-gatherart', "Evaluating Amazon URL: " . $url, '5');
$snoopy = new Snoopy(); $snoopy = new Snoopy();
if(Config::get('proxy_host') AND Config::get('proxy_port')) { if (Config::get('proxy_host') AND Config::get('proxy_port')) {
$snoopy->proxy_user = Config::get('proxy_host'); $snoopy->proxy_user = Config::get('proxy_host');
$snoopy->proxy_port = Config::get('proxy_port'); $snoopy->proxy_port = Config::get('proxy_port');
$snoopy->proxy_user = Config::get('proxy_user'); $snoopy->proxy_user = Config::get('proxy_user');
@ -819,8 +818,8 @@ class Art extends database_object {
* This takes keywords and performs a search of the Amazon website * This takes keywords and performs a search of the Amazon website
* for the art. It returns an array of found objects with mime/url keys * for the art. It returns an array of found objects with mime/url keys
*/ */
public function gather_amazon($limit = 5, $keywords = '') { public function gather_amazon($limit = 5, $keywords = '')
{
$images = array(); $images = array();
$final_results = array(); $final_results = array();
$possible_keys = array( $possible_keys = array(
@ -851,7 +850,7 @@ class Art extends database_object {
// Create the Search Object // Create the Search Object
$amazon = new AmazonSearch(Config::get('amazon_developer_public_key'), Config::get('amazon_developer_private_key'), $amazon_base); $amazon = new AmazonSearch(Config::get('amazon_developer_public_key'), Config::get('amazon_developer_private_key'), $amazon_base);
if(Config::get('proxy_host') AND Config::get('proxy_port')) { if (Config::get('proxy_host') AND Config::get('proxy_port')) {
$proxyhost = Config::get('proxy_host'); $proxyhost = Config::get('proxy_host');
$proxyport = Config::get('proxy_port'); $proxyport = Config::get('proxy_port');
$proxyuser = Config::get('proxy_user'); $proxyuser = Config::get('proxy_user');
@ -917,14 +916,11 @@ class Art extends database_object {
// Rudimentary image type detection, only JPG and GIF allowed. // Rudimentary image type detection, only JPG and GIF allowed.
if (substr($result[$key], -4 == '.jpg')) { if (substr($result[$key], -4 == '.jpg')) {
$mime = "image/jpeg"; $mime = "image/jpeg";
} } elseif (substr($result[$key], -4 == '.gif')) {
elseif (substr($result[$key], -4 == '.gif')) {
$mime = "image/gif"; $mime = "image/gif";
} } elseif (substr($result[$key], -4 == '.png')) {
elseif (substr($result[$key], -4 == '.png')) {
$mime = "image/png"; $mime = "image/png";
} } else {
else {
/* Just go to the next result */ /* Just go to the next result */
continue; continue;
} }
@ -952,8 +948,8 @@ class Art extends database_object {
* If a limit is passed or the preferred filename is found the current * If a limit is passed or the preferred filename is found the current
* results set is returned * results set is returned
*/ */
public function gather_folder($limit = 5) { public function gather_folder($limit = 5)
{
$media = new Album($this->uid); $media = new Album($this->uid);
$songs = $media->get_songs(); $songs = $media->get_songs();
$results = array(); $results = array();
@ -1031,7 +1027,7 @@ class Art extends database_object {
'file' => $full_filename, 'file' => $full_filename,
'mime' => 'image/' . $extension 'mime' => 'image/' . $extension
); );
break; break;
} }
debug_event('folder_art', "Found image file: $file", 5); debug_event('folder_art', "Found image file: $file", 5);
@ -1065,8 +1061,8 @@ class Art extends database_object {
* This looks for the art in the meta-tags of the file * This looks for the art in the meta-tags of the file
* itself * itself
*/ */
public function gather_tags($limit = 5) { public function gather_tags($limit = 5)
{
// We need the filenames // We need the filenames
$album = new Album($this->uid); $album = new Album($this->uid);
@ -1079,8 +1075,7 @@ class Art extends database_object {
$song = new Song($song_id); $song = new Song($song_id);
// If we find a good one, stop looking // If we find a good one, stop looking
$getID3 = new getID3(); $getID3 = new getID3();
try { $id3 = $getID3->analyze($song->file); } try { $id3 = $getID3->analyze($song->file); } catch (Exception $error) {
catch (Exception $error) {
debug_event('getid3', $error->message, 1); debug_event('getid3', $error->message, 1);
} }
@ -1116,8 +1111,8 @@ class Art extends database_object {
* gather_google * gather_google
* Raw google search to retrieve the art, not very reliable * Raw google search to retrieve the art, not very reliable
*/ */
public function gather_google($limit = 5) { public function gather_google($limit = 5)
{
$images = array(); $images = array();
$media = new $this->type($this->uid); $media = new $this->type($this->uid);
$media->format(); $media->format();
@ -1152,8 +1147,8 @@ class Art extends database_object {
* This returns the art from lastfm. It doesn't currently require an * This returns the art from lastfm. It doesn't currently require an
* account but may in the future. * account but may in the future.
*/ */
public function gather_lastfm($limit, $options = false) { public function gather_lastfm($limit, $options = false)
{
// Create the parser object // Create the parser object
$lastfm = new LastFMSearch(); $lastfm = new LastFMSearch();
@ -1162,8 +1157,7 @@ class Art extends database_object {
if (is_array($options)) { if (is_array($options)) {
$artist = $options['artist']; $artist = $options['artist'];
$album = $options['album_name']; $album = $options['album_name'];
} } else {
else {
$media = new Album($this->uid); $media = new Album($this->uid);
$media->format(); $media->format();
$artist = $media->artist_name; $artist = $media->artist_name;
@ -1172,7 +1166,7 @@ class Art extends database_object {
break; break;
} }
if(Config::get('proxy_host') AND Config::get('proxy_port')) { if (Config::get('proxy_host') AND Config::get('proxy_port')) {
$proxyhost = Config::get('proxy_host'); $proxyhost = Config::get('proxy_host');
$proxyport = Config::get('proxy_port'); $proxyport = Config::get('proxy_port');
$proxyuser = Config::get('proxy_user'); $proxyuser = Config::get('proxy_user');
@ -1195,7 +1189,7 @@ class Art extends database_object {
debug_event('LastFM', 'Detected as noimage, skipped ' . $url, 3); debug_event('LastFM', 'Detected as noimage, skipped ' . $url, 3);
continue; continue;
} }
// HACK: we shouldn't rely on the extension to determine file type // HACK: we shouldn't rely on the extension to determine file type
$results = pathinfo($url); $results = pathinfo($url);
$mime = 'image/' . $results['extension']; $mime = 'image/' . $results['extension'];

View file

@ -20,8 +20,8 @@
* *
*/ */
class Artist extends database_object { class Artist extends database_object
{
/* Variables from DB */ /* Variables from DB */
public $id; public $id;
public $name; public $name;
@ -40,8 +40,8 @@ class Artist extends database_object {
* Artist class, for modifing a artist * Artist class, for modifing a artist
* Takes the ID of the artist and pulls the info from the db * Takes the ID of the artist and pulls the info from the db
*/ */
public function __construct($id='',$catalog_init=0) { public function __construct($id='',$catalog_init=0)
{
/* If they failed to pass in an id, just run for it */ /* If they failed to pass in an id, just run for it */
if (!$id) { return false; } if (!$id) { return false; }
@ -62,8 +62,8 @@ class Artist extends database_object {
* This is used by the metadata class specifically but fills out a Artist object * This is used by the metadata class specifically but fills out a Artist object
* based on a key'd array, it sets $_fake to true * based on a key'd array, it sets $_fake to true
*/ */
public static function construct_from_array($data) { public static function construct_from_array($data)
{
$artist = new Artist(0); $artist = new Artist(0);
foreach ($data as $key=>$value) { foreach ($data as $key=>$value) {
$artist->$key = $value; $artist->$key = $value;
@ -81,15 +81,17 @@ class Artist extends database_object {
* *
* This cleans out unused artists * This cleans out unused artists
*/ */
public static function gc() { public static function gc()
{
Dba::write('DELETE FROM `artist` USING `artist` LEFT JOIN `song` ON `song`.`artist` = `artist`.`id` WHERE `song`.`id` IS NULL'); Dba::write('DELETE FROM `artist` USING `artist` LEFT JOIN `song` ON `song`.`artist` = `artist`.`id` WHERE `song`.`id` IS NULL');
} }
/** /**
* this attempts to build a cache of the data from the passed albums all in one query * this attempts to build a cache of the data from the passed albums all in one query
*/ */
public static function build_cache($ids,$extra=false) { public static function build_cache($ids,$extra=false)
if(!is_array($ids) OR !count($ids)) { return false; } {
if (!is_array($ids) OR !count($ids)) { return false; }
$idlist = '(' . implode(',', $ids) . ')'; $idlist = '(' . implode(',', $ids) . ')';
@ -103,7 +105,7 @@ class Artist extends database_object {
// If we need to also pull the extra information, this is normally only used when we are doing the human display // If we need to also pull the extra information, this is normally only used when we are doing the human display
if ($extra) { if ($extra) {
$sql = "SELECT `song`.`artist`, COUNT(`song`.`id`) AS `song_count`, COUNT(DISTINCT `song`.`album`) AS `album_count`, SUM(`song`.`time`) AS `time` FROM `song` WHERE `song`.`artist` IN $idlist GROUP BY `song`.`artist`"; $sql = "SELECT `song`.`artist`, COUNT(`song`.`id`) AS `song_count`, COUNT(DISTINCT `song`.`album`) AS `album_count`, SUM(`song`.`time`) AS `time` FROM `song` WHERE `song`.`artist` IN $idlist GROUP BY `song`.`artist`";
debug_event("Artist", "build_cache sql: " . $sql, "6"); debug_event("Artist", "build_cache sql: " . $sql, "6");
$db_results = Dba::read($sql); $db_results = Dba::read($sql);
@ -124,8 +126,8 @@ class Artist extends database_object {
* get_from_name * get_from_name
* This gets an artist object based on the artist name * This gets an artist object based on the artist name
*/ */
public static function get_from_name($name) { public static function get_from_name($name)
{
$name = Dba::escape($name); $name = Dba::escape($name);
$sql = "SELECT `id` FROM `artist` WHERE `name`='$name'"; $sql = "SELECT `id` FROM `artist` WHERE `name`='$name'";
$db_results = Dba::write($sql); $db_results = Dba::write($sql);
@ -143,23 +145,20 @@ class Artist extends database_object {
* gets the album ids that this artist is a part * gets the album ids that this artist is a part
* of * of
*/ */
public function get_albums($catalog = null) { public function get_albums($catalog = null)
{
if($catalog) { if ($catalog) {
$catalog_join = "LEFT JOIN `catalog` ON `catalog`.`id` = `song`.`catalog`"; $catalog_join = "LEFT JOIN `catalog` ON `catalog`.`id` = `song`.`catalog`";
$catalog_where = "AND `catalog`.`id` = '$catalog'"; $catalog_where = "AND `catalog`.`id` = '$catalog'";
} }
$results = array(); $results = array();
$sql_sort = 'ORDER BY `album`.`name`,`album`.`disk`,`album`.`year`'; $sql_sort = 'ORDER BY `album`.`name`,`album`.`disk`,`album`.`year`';
$sort_type = Config::get('album_sort'); $sort_type = Config::get('album_sort');
if ($sort_type == 'year_asc') { $sql_sort = 'ORDER BY `album`.`year` ASC'; } if ($sort_type == 'year_asc') { $sql_sort = 'ORDER BY `album`.`year` ASC'; } elseif ($sort_type == 'year_desc') { $sql_sort = 'ORDER BY `album`.`year` DESC'; } elseif ($sort_type == 'name_asc') { $sql_sort = 'ORDER BY `album`.`name` ASC'; } elseif ($sort_type == 'name_desc') { $sql_sort = 'ORDER BY `album`.`name` DESC'; }
elseif ($sort_type == 'year_desc') { $sql_sort = 'ORDER BY `album`.`year` DESC'; }
elseif ($sort_type == 'name_asc') { $sql_sort = 'ORDER BY `album`.`name` ASC'; }
elseif ($sort_type == 'name_desc') { $sql_sort = 'ORDER BY `album`.`name` DESC'; }
$sql = "SELECT `album`.`id` FROM album LEFT JOIN `song` ON `song`.`album`=`album`.`id` $catalog_join " . $sql = "SELECT `album`.`id` FROM album LEFT JOIN `song` ON `song`.`album`=`album`.`id` $catalog_join " .
"WHERE `song`.`artist`='$this->id' $catalog_where GROUP BY `album`.`id` $sql_sort"; "WHERE `song`.`artist`='$this->id' $catalog_where GROUP BY `album`.`id` $sql_sort";
@ -178,8 +177,8 @@ class Artist extends database_object {
* get_songs * get_songs
* gets the songs for this artist * gets the songs for this artist
*/ */
public function get_songs() { public function get_songs()
{
$sql = "SELECT `song`.`id` FROM `song` WHERE `song`.`artist`='" . Dba::escape($this->id) . "' ORDER BY album, track"; $sql = "SELECT `song`.`id` FROM `song` WHERE `song`.`artist`='" . Dba::escape($this->id) . "' ORDER BY album, track";
$db_results = Dba::read($sql); $db_results = Dba::read($sql);
@ -195,8 +194,8 @@ class Artist extends database_object {
* get_random_songs * get_random_songs
* Gets the songs from this artist in a random order * Gets the songs from this artist in a random order
*/ */
public function get_random_songs() { public function get_random_songs()
{
$results = array(); $results = array();
$sql = "SELECT `id` FROM `song` WHERE `artist`='$this->id' ORDER BY RAND()"; $sql = "SELECT `id` FROM `song` WHERE `artist`='$this->id' ORDER BY RAND()";
@ -214,13 +213,12 @@ class Artist extends database_object {
* _get_extra info * _get_extra info
* This returns the extra information for the artist, this means totals etc * This returns the extra information for the artist, this means totals etc
*/ */
private function _get_extra_info($catalog=FALSE) { private function _get_extra_info($catalog=FALSE)
{
// Try to find it in the cache and save ourselves the trouble // Try to find it in the cache and save ourselves the trouble
if (parent::is_cached('artist_extra',$this->id) ) { if (parent::is_cached('artist_extra',$this->id) ) {
$row = parent::get_from_cache('artist_extra',$this->id); $row = parent::get_from_cache('artist_extra',$this->id);
} } else {
else {
$uid = Dba::escape($this->id); $uid = Dba::escape($this->id);
$sql = "SELECT `song`.`artist`,COUNT(`song`.`id`) AS `song_count`, COUNT(DISTINCT `song`.`album`) AS `album_count`, SUM(`song`.`time`) AS `time` FROM `song` WHERE `song`.`artist`='$uid' "; $sql = "SELECT `song`.`artist`,COUNT(`song`.`id`) AS `song_count`, COUNT(DISTINCT `song`.`album`) AS `album_count`, SUM(`song`.`time`) AS `time` FROM `song` WHERE `song`.`artist`='$uid' ";
if ($catalog) { if ($catalog) {
@ -228,7 +226,7 @@ class Artist extends database_object {
} }
$sql .= "GROUP BY `song`.`artist`"; $sql .= "GROUP BY `song`.`artist`";
$db_results = Dba::read($sql); $db_results = Dba::read($sql);
$row = Dba::fetch_assoc($db_results); $row = Dba::fetch_assoc($db_results);
if (Config::get('show_played_times')) { if (Config::get('show_played_times')) {
@ -253,8 +251,8 @@ class Artist extends database_object {
* so they can be displayed in a table for example * so they can be displayed in a table for example
* it changes the title into a full link. * it changes the title into a full link.
*/ */
public function format() { public function format()
{
/* Combine prefix and name, trim then add ... if needed */ /* Combine prefix and name, trim then add ... if needed */
$name = UI::truncate(trim($this->prefix . " " . $this->name),Config::get('ellipse_threshold_artist')); $name = UI::truncate(trim($this->prefix . " " . $this->name),Config::get('ellipse_threshold_artist'));
$this->f_name = $name; $this->f_name = $name;
@ -295,13 +293,14 @@ class Artist extends database_object {
* *
* Checks for an existing artist; if none exists, insert one. * Checks for an existing artist; if none exists, insert one.
*/ */
public static function check($name, $mbid = null, $readonly = false) { public static function check($name, $mbid = null, $readonly = false)
{
$trimmed = Catalog::trim_prefix(trim($name)); $trimmed = Catalog::trim_prefix(trim($name));
$name = $trimmed['string']; $name = $trimmed['string'];
$prefix = $trimmed['prefix']; $prefix = $trimmed['prefix'];
if ($mbid == '') $mbid = null; if ($mbid == '') $mbid = null;
if (!$name) { if (!$name) {
$name = T_('Unknown (Orphaned)'); $name = T_('Unknown (Orphaned)');
$prefix = null; $prefix = null;
@ -342,8 +341,7 @@ class Artist extends database_object {
$id = $id_array['null']; $id = $id_array['null'];
$exists = true; $exists = true;
} }
} } else {
else {
// Pick one at random // Pick one at random
$id = array_shift($id_array); $id = array_shift($id_array);
$exists = true; $exists = true;
@ -379,8 +377,8 @@ class Artist extends database_object {
* This takes a key'd array of data and updates the current artist * This takes a key'd array of data and updates the current artist
* it will flag songs as neeed * it will flag songs as neeed
*/ */
public function update($data) { public function update($data)
{
// Save our current ID // Save our current ID
$current_id = $this->id; $current_id = $this->id;
@ -412,4 +410,3 @@ class Artist extends database_object {
} // update } // update
} // end of artist class } // end of artist class
?>

View file

@ -26,14 +26,15 @@
* 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
* classes where it didn't belong. * classes where it didn't belong.
*/ */
class Auth { class Auth
{
/** /**
* 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,8 +45,8 @@ class Auth {
* 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='', $relogin = true) { public static function logout($key='', $relogin = true)
{
// 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();
@ -53,8 +54,7 @@ class Auth {
Session::destroy($key); Session::destroy($key);
if ((!$relogin) && Config::get('logout_redirect')) { if ((!$relogin) && Config::get('logout_redirect')) {
$target = Config::get('logout_redirect'); $target = Config::get('logout_redirect');
} } else {
else {
$target = Config::get('web_path') . '/login.php'; $target = Config::get('web_path') . '/login.php';
} }
@ -74,8 +74,7 @@ class Auth {
$results['rfc3514'] = '<script type="text/javascript">reloadRedirect("' . $target . '")</script>'; $results['rfc3514'] = '<script type="text/javascript">reloadRedirect("' . $target . '")</script>';
echo xml_from_array($results); echo xml_from_array($results);
} } else {
else {
/* Redirect them to the login page */ /* Redirect them to the login page */
header('Location: ' . $target); header('Location: ' . $target);
} }
@ -89,11 +88,12 @@ class Auth {
* This takes a username and password and then returns the results * This takes a username and password and then returns the results
* based on what happens when we try to do the auth. * based on what happens when we try to do the auth.
*/ */
public static function login($username, $password) { public static function login($username, $password)
{
foreach (Config::get('auth_methods') as $method) { foreach (Config::get('auth_methods') as $method) {
$function_name = $method . '_auth'; $function_name = $method . '_auth';
if (!method_exists('Auth', $function_name)) { if (!method_exists('Auth', $function_name)) {
continue; continue;
} }
@ -109,8 +109,8 @@ class Auth {
* *
* This is the core function of our built-in authentication. * This is the core function of our built-in authentication.
*/ */
private static function mysql_auth($username, $password) { private static function mysql_auth($username, $password)
{
if (strlen($password) && strlen($username)) { if (strlen($password) && strlen($username)) {
$sql = 'SELECT `password` FROM `user` WHERE `username` = ?'; $sql = 'SELECT `password` FROM `user` WHERE `username` = ?';
$db_results = Dba::read($sql, array($username)); $db_results = Dba::read($sql, array($username));
@ -122,7 +122,7 @@ class Auth {
// doesn't break things. // doesn't break things.
// FIXME: Break things in the future. // FIXME: Break things in the future.
$hashed_password[] = hash('sha256', $password); $hashed_password[] = hash('sha256', $password);
$hashed_password[] = hash('sha256', $hashed_password[] = hash('sha256',
Dba::escape(stripslashes(htmlspecialchars(strip_tags($password))))); Dba::escape(stripslashes(htmlspecialchars(strip_tags($password)))));
// Automagically update the password if it's old and busted. // Automagically update the password if it's old and busted.
@ -151,10 +151,11 @@ class Auth {
/** /**
* pam_auth * pam_auth
* *
* Check to make sure the pam_auth function is implemented (module is * Check to make sure the pam_auth function is implemented (module is
* installed), then check the credentials. * installed), then check the credentials.
*/ */
private static function pam_auth($username, $password) { private static function pam_auth($username, $password)
{
if (!function_exists('pam_auth')) { if (!function_exists('pam_auth')) {
$results['success'] = false; $results['success'] = false;
$results['error'] = 'The PAM PHP module is not installed'; $results['error'] = 'The PAM PHP module is not installed';
@ -167,8 +168,7 @@ class Auth {
$results['success'] = true; $results['success'] = true;
$results['type'] = 'pam'; $results['type'] = 'pam';
$results['username'] = $username; $results['username'] = $username;
} } else {
else {
$results['success'] = false; $results['success'] = false;
$results['error'] = 'PAM login attempt failed'; $results['error'] = 'PAM login attempt failed';
} }
@ -182,7 +182,8 @@ class Auth {
* Calls an external program compatible with mod_authnz_external * Calls an external program compatible with mod_authnz_external
* such as pwauth. * such as pwauth.
*/ */
private static function external_auth($username, $password) { private static function external_auth($username, $password)
{
$authenticator = Config::get('external_authenticator'); $authenticator = Config::get('external_authenticator');
if (!$authenticator) { if (!$authenticator) {
return array( return array(
@ -207,8 +208,7 @@ class Auth {
debug_event('external_auth', $stderr, 5); debug_event('external_auth', $stderr, 5);
} }
fclose($pipes[2]); fclose($pipes[2]);
} } else {
else {
return array( return array(
'success' => false, 'success' => false,
'error' => 'Failed to run external authenticator' 'error' => 'Failed to run external authenticator'
@ -237,13 +237,13 @@ class Auth {
* provided. * provided.
* Step three, figure out if they are authorized to use ampache: * Step three, figure out if they are authorized to use ampache:
* TODO: in config but unimplemented: * TODO: in config but unimplemented:
* * require-dn "Grant access if the DN in the directive matches * * require-dn "Grant access if the DN in the directive matches
* the DN fetched from the LDAP directory" * the DN fetched from the LDAP directory"
* * require-attribute "an attribute fetched from the LDAP * * require-attribute "an attribute fetched from the LDAP
* directory matches the given value" * 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');
@ -296,7 +296,7 @@ class Auth {
if ($retval) { if ($retval) {
// When the current user needs to be in // When the current user needs to be in
// a specific group to access Ampache, // a specific group to access Ampache,
// check whether the 'member' list of // check whether the 'member' list of
// the group contains the DN // the group contains the DN
if ($require_group) { if ($require_group) {
$group_result = ldap_read($ldap_link, $require_group, 'objectclass=*', array('member')); $group_result = ldap_read($ldap_link, $require_group, 'objectclass=*', array('member'));
@ -351,7 +351,8 @@ class Auth {
* http_auth * http_auth
* This auth method relies on HTTP auth from the webserver * This auth method relies on HTTP auth from the webserver
*/ */
private static function http_auth($username, $password) { private static function http_auth($username, $password)
{
if (($_SERVER['REMOTE_USER'] == $username) || if (($_SERVER['REMOTE_USER'] == $username) ||
($_SERVER['HTTP_REMOTE_USER'] == $username)) { ($_SERVER['HTTP_REMOTE_USER'] == $username)) {
$results['success'] = true; $results['success'] = true;
@ -359,8 +360,7 @@ class Auth {
$results['username'] = $username; $results['username'] = $username;
$results['name'] = $username; $results['name'] = $username;
$results['email'] = ''; $results['email'] = '';
} } else {
else {
$results['success'] = false; $results['success'] = false;
$results['error'] = 'HTTP auth login attempt failed'; $results['error'] = 'HTTP auth login attempt failed';
} }
@ -368,4 +368,3 @@ class Auth {
} // http_auth } // http_auth
} }
?>

View file

@ -29,15 +29,15 @@
* calling the correct template for the object we are displaying * calling the correct template for the object we are displaying
* *
*/ */
class Browse extends Query { class Browse extends Query
{
/** /**
* set_simple_browse * set_simple_browse
* This sets the current browse object to a 'simple' browse method * This sets the current browse object to a 'simple' browse method
* which means use the base query provided and expand from there * which means use the base query provided and expand from there
*/ */
public function set_simple_browse($value) { public function set_simple_browse($value)
{
$this->set_is_simple($value); $this->set_is_simple($value);
} // set_simple_browse } // set_simple_browse
@ -46,8 +46,8 @@ class Browse extends Query {
* add_supplemental_object * add_supplemental_object
* Legacy function, need to find a better way to do that * Legacy function, need to find a better way to do that
*/ */
public function add_supplemental_object($class, $uid) { public function add_supplemental_object($class, $uid)
{
$_SESSION['browse']['supplemental'][$this->id][$class] = intval($uid); $_SESSION['browse']['supplemental'][$this->id][$class] = intval($uid);
return true; return true;
@ -59,8 +59,8 @@ class Browse extends Query {
* This returns an array of 'class','id' for additional objects that * This returns an array of 'class','id' for additional objects that
* need to be created before we start this whole browsing thing. * need to be created before we start this whole browsing thing.
*/ */
public function get_supplemental_objects() { public function get_supplemental_objects()
{
$objects = $_SESSION['browse']['supplemental'][$this->id]; $objects = $_SESSION['browse']['supplemental'][$this->id];
if (!is_array($objects)) { $objects = array(); } if (!is_array($objects)) { $objects = array(); }
@ -75,24 +75,23 @@ class Browse extends Query {
* and requires the correct template based on the * and requires the correct template based on the
* type that we are currently browsing * type that we are currently browsing
*/ */
public function show_objects($object_ids = null) { public function show_objects($object_ids = null)
{
if ($this->is_simple() || ! is_array($object_ids)) { if ($this->is_simple() || ! is_array($object_ids)) {
$object_ids = $this->get_saved(); $object_ids = $this->get_saved();
} } else {
else {
$this->save_objects($object_ids); $this->save_objects($object_ids);
} }
// Limit is based on the user's preferences if this is not a // Limit is based on the user's preferences if this is not a
// simple browse because we've got too much here // simple browse because we've got too much here
if ((count($object_ids) > $this->get_start()) && if ((count($object_ids) > $this->get_start()) &&
! $this->is_simple() && ! $this->is_simple() &&
! $this->is_static_content()) { ! $this->is_static_content()) {
$object_ids = array_slice( $object_ids = array_slice(
$object_ids, $object_ids,
$this->get_start(), $this->get_start(),
$this->get_offset(), $this->get_offset(),
true true
); );
} }
@ -109,8 +108,7 @@ class Browse extends Query {
// Format any matches we have so we can show them to the masses // Format any matches we have so we can show them to the masses
if ($filter_value = $this->get_filter('alpha_match')) { if ($filter_value = $this->get_filter('alpha_match')) {
$match = ' (' . $filter_value . ')'; $match = ' (' . $filter_value . ')';
} } elseif ($filter_value = $this->get_filter('starts_with')) {
elseif ($filter_value = $this->get_filter('starts_with')) {
$match = ' (' . $filter_value . ')'; $match = ' (' . $filter_value . ')';
} elseif ($filter_value = $this->get_filter('catalog')) { } elseif ($filter_value = $this->get_filter('catalog')) {
// Get the catalog title // Get the catalog title
@ -223,12 +221,13 @@ class Browse extends Query {
* set_filter_from_request * set_filter_from_request
* //FIXME * //FIXME
*/ */
public function set_filter_from_request($request) { public function set_filter_from_request($request)
foreach($request as $key => $value) { {
foreach ($request as $key => $value) {
//reinterpret v as a list of int //reinterpret v as a list of int
$list = explode(',', $value); $list = explode(',', $value);
$ok = true; $ok = true;
foreach($list as $item) { foreach ($list as $item) {
if (!is_numeric($item)) { if (!is_numeric($item)) {
$ok = false; $ok = false;
break; break;
@ -238,8 +237,7 @@ class Browse extends Query {
if (sizeof($list) == 1) { if (sizeof($list) == 1) {
$this->set_filter($key, $list[0]); $this->set_filter($key, $list[0]);
} }
} } else {
else {
$this->set_filter($key, $list); $this->set_filter($key, $list);
} }
} }

View file

@ -27,8 +27,8 @@
* it contains functions for creating/listing/updated the catalogs. * it contains functions for creating/listing/updated the catalogs.
* *
*/ */
abstract class Catalog extends database_object { abstract class Catalog extends database_object
{
public $name; public $name;
public $last_update; public $last_update;
public $last_add; public $last_add;
@ -48,7 +48,7 @@ abstract class Catalog extends database_object {
private static $albums = array(); private static $albums = array();
private static $artists = array(); private static $artists = array();
private static $tags = array(); private static $tags = array();
abstract public function get_type(); abstract public function get_type();
abstract public function get_description(); abstract public function get_description();
abstract public function get_version(); abstract public function get_version();
@ -61,41 +61,41 @@ abstract class Catalog extends database_object {
abstract public function catalog_fields(); abstract public function catalog_fields();
abstract public function get_rel_path($file_path); abstract public function get_rel_path($file_path);
abstract public function prepare_media($media); abstract public function prepare_media($media);
/** /**
* uninstall * uninstall
* This removes the remote catalog * This removes the remote catalog
*/ */
public function uninstall() { public function uninstall()
{
$sql = "DELETE FROM `catalog` WHERE `catalog_type` = ?";
$db_results = Dba::query($sql, array($this->get_type()));
$sql = "DELETE FROM `catalog` WHERE `catalog_type` = ?"; $sql = "DROP TABLE `catalog_" . $this->get_type() ."`";
$db_results = Dba::query($sql, array($this->get_type())); $db_results = Dba::query($sql);
$sql = "DROP TABLE `catalog_" . $this->get_type() ."`";
$db_results = Dba::query($sql);
return true; return true;
} // uninstall } // uninstall
public static function create_from_id($id) { public static function create_from_id($id)
{
$sql = 'SELECT `catalog_type` FROM `catalog` WHERE `id` = ?'; $sql = 'SELECT `catalog_type` FROM `catalog` WHERE `id` = ?';
$db_results = Dba::read($sql, array($id)); $db_results = Dba::read($sql, array($id));
if ($results = Dba::fetch_assoc($db_results)) { if ($results = Dba::fetch_assoc($db_results)) {
return self::create_catalog_type($results['catalog_type'], $id); return self::create_catalog_type($results['catalog_type'], $id);
} }
return null; return null;
} }
/** /**
* create_catalog_type * create_catalog_type
* This function attempts to create a catalog type * This function attempts to create a catalog type
* all Catalog modules should be located in /modules/catalog/<name>.class.php * all Catalog modules should be located in /modules/catalog/<name>.class.php
*/ */
public static function create_catalog_type($type, $id=0) { public static function create_catalog_type($type, $id=0)
{
if (!$type) { return false; } if (!$type) { return false; }
$filename = Config::get('prefix') . '/modules/catalog/' . $type . '.catalog.php'; $filename = Config::get('prefix') . '/modules/catalog/' . $type . '.catalog.php';
@ -121,9 +121,9 @@ abstract class Catalog extends database_object {
} }
} // create_catalog_type } // create_catalog_type
public static function show_catalog_types($divback = 'catalog_type_fields') {
public static function show_catalog_types($divback = 'catalog_type_fields')
{
echo "<script language=\"javascript\" type=\"text/javascript\">" . echo "<script language=\"javascript\" type=\"text/javascript\">" .
"var type_fields = new Array();" . "var type_fields = new Array();" .
"type_fields['none'] = '';"; "type_fields['none'] = '';";
@ -141,7 +141,7 @@ abstract class Catalog extends database_object {
} }
foreach ($fields as $key=>$field) { foreach ($fields as $key=>$field) {
echo "<tr><td style='width: 25%;'>" . $field['description'] . ":</td><td>"; echo "<tr><td style='width: 25%;'>" . $field['description'] . ":</td><td>";
switch ($field['type']) { switch ($field['type']) {
case 'checkbox': case 'checkbox':
echo "<input type='checkbox' size='10' name='" . $key . "' value='1' " . (($field['value']) ? 'checked' : '') . "/>"; echo "<input type='checkbox' size='10' name='" . $key . "' value='1' " . (($field['value']) ? 'checked' : '') . "/>";
@ -167,13 +167,13 @@ abstract class Catalog extends database_object {
"} </script>" . "} </script>" .
"<select name=\"type\" id=\"catalog_type\" onChange=\"catalogTypeChanged();\">" . $seltypes . "</select>"; "<select name=\"type\" id=\"catalog_type\" onChange=\"catalogTypeChanged();\">" . $seltypes . "</select>";
} }
/** /**
* get_catalog_types * get_catalog_types
* This returns the catalog types that are available * This returns the catalog types that are available
*/ */
public static function get_catalog_types() { public static function get_catalog_types()
{
/* First open the dir */ /* First open the dir */
$handle = opendir(Config::get('prefix') . '/modules/catalog'); $handle = opendir(Config::get('prefix') . '/modules/catalog');
@ -199,24 +199,26 @@ abstract class Catalog extends database_object {
return $results; return $results;
} // get_catalog_types } // get_catalog_types
public static function is_audio_file($file) { public static function is_audio_file($file)
{
$pattern = "/\.(" . Config::get('catalog_file_pattern'); $pattern = "/\.(" . Config::get('catalog_file_pattern');
if ($options['parse_m3u']) { if ($options['parse_m3u']) {
$pattern .= "|m3u)$/i"; $pattern .= "|m3u)$/i";
} } else {
else {
$pattern .= ")$/i"; $pattern .= ")$/i";
} }
return preg_match($pattern, $file); return preg_match($pattern, $file);
} }
public static function is_video_file($file) { public static function is_video_file($file)
{
$video_pattern = "/\.(" . Config::get('catalog_video_pattern') . ")$/i"; $video_pattern = "/\.(" . Config::get('catalog_video_pattern') . ")$/i";
return preg_match($video_pattern, $file); return preg_match($video_pattern, $file);
} }
public function get_info($id, $table = 'catalog') { public function get_info($id, $table = 'catalog')
{
$info = parent::get_info($id, $table); $info = parent::get_info($id, $table);
$table = 'catalog_' . $this->get_type(); $table = 'catalog_' . $this->get_type();
@ -232,7 +234,7 @@ abstract class Catalog extends database_object {
} }
} }
} }
return $info; return $info;
} }
@ -241,7 +243,8 @@ abstract class Catalog extends database_object {
* *
* This populates an array which is used to speed up the add process. * This populates an array which is used to speed up the add process.
*/ */
protected function _create_filecache() { protected function _create_filecache()
{
if (count($this->_filecache) == 0) { if (count($this->_filecache) == 0) {
// Get _EVERYTHING_ // Get _EVERYTHING_
$sql = 'SELECT `id`, `file` FROM `song` WHERE `catalog` = ?'; $sql = 'SELECT `id`, `file` FROM `song` WHERE `catalog` = ?';
@ -268,20 +271,21 @@ abstract class Catalog extends database_object {
* *
* This makes the object human-readable. * This makes the object human-readable.
*/ */
public function format() { public function format()
{
$this->f_name = UI::truncate($this->name, $this->f_name = UI::truncate($this->name,
Config::get('ellipse_threshold_title')); Config::get('ellipse_threshold_title'));
$this->f_name_link = '<a href="' . Config::get('web_path') . $this->f_name_link = '<a href="' . Config::get('web_path') .
'/admin/catalog.php?action=show_customize_catalog&catalog_id=' . '/admin/catalog.php?action=show_customize_catalog&catalog_id=' .
$this->id . '" title="' . scrub_out($this->name) . '">' . $this->id . '" title="' . scrub_out($this->name) . '">' .
scrub_out($this->f_name) . '</a>'; scrub_out($this->f_name) . '</a>';
$this->f_update = $this->last_update $this->f_update = $this->last_update
? date('d/m/Y h:i', $this->last_update) ? date('d/m/Y h:i', $this->last_update)
: T_('Never'); : T_('Never');
$this->f_add = $this->last_add $this->f_add = $this->last_add
? date('d/m/Y h:i', $this->last_add) ? date('d/m/Y h:i', $this->last_add)
: T_('Never'); : T_('Never');
$this->f_clean = $this->last_clean $this->f_clean = $this->last_clean
? date('d/m/Y h:i', $this->last_clean) ? date('d/m/Y h:i', $this->last_clean)
: T_('Never'); : T_('Never');
} }
@ -292,7 +296,8 @@ abstract class Catalog extends database_object {
* Pull all the current catalogs and return an array of ids * Pull all the current catalogs and return an array of ids
* of what you find * of what you find
*/ */
public static function get_catalogs() { public static function get_catalogs()
{
$sql = "SELECT `id` FROM `catalog` ORDER BY `name`"; $sql = "SELECT `id` FROM `catalog` ORDER BY `name`";
$db_results = Dba::read($sql); $db_results = Dba::read($sql);
@ -312,7 +317,8 @@ abstract class Catalog extends database_object {
* objects that are associated with this catalog. This is used * objects that are associated with this catalog. This is used
* to build the stats box, it also calculates time. * to build the stats box, it also calculates time.
*/ */
public static function get_stats($catalog_id = null) { public static function get_stats($catalog_id = null)
{
$results = self::count_songs($catalog_id); $results = self::count_songs($catalog_id);
$results = array_merge(User::count(), $results); $results = array_merge(User::count(), $results);
$results['tags'] = self::count_tags(); $results['tags'] = self::count_tags();
@ -340,8 +346,8 @@ abstract class Catalog extends database_object {
* *
* This creates a new catalog entry and associate it to current instance * This creates a new catalog entry and associate it to current instance
*/ */
public static function create($data) { public static function create($data)
{
$name = $data['name']; $name = $data['name'];
$type = $data['type']; $type = $data['type'];
$rename_pattern = $data['rename_pattern']; $rename_pattern = $data['rename_pattern'];
@ -367,7 +373,7 @@ abstract class Catalog extends database_object {
debug_event('catalog', 'Insert failed: ' . json_encode($data), 2); debug_event('catalog', 'Insert failed: ' . json_encode($data), 2);
return false; return false;
} }
$classname = 'Catalog_' . $type; $classname = 'Catalog_' . $type;
if (!$classname::create_type($insert_id, $data)) { if (!$classname::create_type($insert_id, $data)) {
$sql = 'DELETE FROM `catalog` WHERE `id` = ?'; $sql = 'DELETE FROM `catalog` WHERE `id` = ?';
@ -384,7 +390,8 @@ abstract class Catalog extends database_object {
* *
* This returns the current number of video files in the database. * This returns the current number of video files in the database.
*/ */
public static function count_videos($id = null) { public static function count_videos($id = null)
{
$sql = 'SELECT COUNT(`id`) FROM `video` '; $sql = 'SELECT COUNT(`id`) FROM `video` ';
if ($id) { if ($id) {
$sql .= 'WHERE `catalog` = ?'; $sql .= 'WHERE `catalog` = ?';
@ -400,7 +407,8 @@ abstract class Catalog extends database_object {
* *
* This returns the current number of unique tags in the database. * This returns the current number of unique tags in the database.
*/ */
public static function count_tags($id = null) { public static function count_tags($id = null)
{
// FIXME: Ignores catalog_id // FIXME: Ignores catalog_id
$sql = "SELECT COUNT(`id`) FROM `tag`"; $sql = "SELECT COUNT(`id`) FROM `tag`";
$db_results = Dba::read($sql); $db_results = Dba::read($sql);
@ -415,7 +423,8 @@ abstract class Catalog extends database_object {
* This returns the current number of songs, albums, and artists * This returns the current number of songs, albums, and artists
* in this catalog. * in this catalog.
*/ */
public static function count_songs($id = null) { public static function count_songs($id = null)
{
$where_sql = $id ? 'WHERE `catalog` = ?' : ''; $where_sql = $id ? 'WHERE `catalog` = ?' : '';
$params = $id ? array($id) : null; $params = $id ? array($id) : null;
@ -453,7 +462,8 @@ abstract class Catalog extends database_object {
* This returns an array of ids of albums that have songs in this * This returns an array of ids of albums that have songs in this
* catalog * catalog
*/ */
public function get_album_ids() { public function get_album_ids()
{
$results = array(); $results = array();
$sql = 'SELECT DISTINCT(`song`.`album`) FROM `song` WHERE `song`.`catalog` = ?'; $sql = 'SELECT DISTINCT(`song`.`album`) FROM `song` WHERE `song`.`catalog` = ?';
@ -465,27 +475,28 @@ abstract class Catalog extends database_object {
return $results; return $results;
} }
/** /**
* get_artist * get_artist
* *
* This returns an array of ids of artists that have songs in the catalogs parameter * This returns an array of ids of artists that have songs in the catalogs parameter
*/ */
public static function get_artists($catalogs = null) { public static function get_artists($catalogs = null)
if(is_array($catalogs) && count($catalogs)) { {
if (is_array($catalogs) && count($catalogs)) {
$catlist = '(' . implode(',', $catalogs) . ')'; $catlist = '(' . implode(',', $catalogs) . ')';
$sql_where = "WHERE `song`.`catalog` IN $catlist"; $sql_where = "WHERE `song`.`catalog` IN $catlist";
} }
$sql = "SELECT `artist`.id, `artist`.`name` FROM `song` LEFT JOIN `artist` ON `artist`.`id` = `song`.`artist` $sql_where GROUP BY `song`.artist ORDER BY `artist`.`name`"; $sql = "SELECT `artist`.id, `artist`.`name` FROM `song` LEFT JOIN `artist` ON `artist`.`id` = `song`.`artist` $sql_where GROUP BY `song`.artist ORDER BY `artist`.`name`";
$results = array(); $results = array();
$db_results = Dba::read($sql); $db_results = Dba::read($sql);
while ($r = Dba::fetch_assoc($db_results)) { while ($r = Dba::fetch_assoc($db_results)) {
$results[] = Artist::construct_from_array($r); $results[] = Artist::construct_from_array($r);
} }
return $results; return $results;
} }
@ -496,7 +507,8 @@ abstract class Catalog extends database_object {
* This runs through all of the needs art albums and trys * This runs through all of the needs art albums and trys
* to find the art for them from the mp3s * to find the art for them from the mp3s
*/ */
public function gather_art() { public function gather_art()
{
// Make sure they've actually got methods // Make sure they've actually got methods
$art_order = Config::get('art_order'); $art_order = Config::get('art_order');
if (!count($art_order)) { if (!count($art_order)) {
@ -542,8 +554,7 @@ abstract class Catalog extends database_object {
} }
} }
} } else {
else {
debug_event('gather_art', 'Image less than 5 chars, not inserting', 3); debug_event('gather_art', 'Image less than 5 chars, not inserting', 3);
} }
$art_found++; $art_found++;
@ -569,7 +580,8 @@ abstract class Catalog extends database_object {
* *
* Returns an array of song objects. * Returns an array of song objects.
*/ */
public function get_songs() { public function get_songs()
{
$results = array(); $results = array();
$sql = "SELECT `id` FROM `song` WHERE `catalog` = ? AND `enabled`='1'"; $sql = "SELECT `id` FROM `song` WHERE `catalog` = ? AND `enabled`='1'";
@ -588,7 +600,8 @@ abstract class Catalog extends database_object {
* This runs through all of the albums and tries to dump the * This runs through all of the albums and tries to dump the
* art for them into the 'folder.jpg' file in the appropriate dir. * art for them into the 'folder.jpg' file in the appropriate dir.
*/ */
public function dump_album_art($methods = array()) { public function dump_album_art($methods = array())
{
// Get all of the albums in this catalog // Get all of the albums in this catalog
$albums = $this->get_album_ids(); $albums = $this->get_album_ids();
@ -647,8 +660,7 @@ abstract class Catalog extends database_object {
echo "Written: $i. . .\n"; echo "Written: $i. . .\n";
debug_event('art_write',"$album->name Art written to $file",'5'); debug_event('art_write',"$album->name Art written to $file",'5');
} }
} } else {
else {
debug_event('art_write',"Unable to open $file for writing", 5); debug_event('art_write',"Unable to open $file for writing", 5);
echo "Error: unable to open file for writing [$file]\n"; echo "Error: unable to open file for writing [$file]\n";
} }
@ -663,8 +675,8 @@ abstract class Catalog extends database_object {
* update_last_update * update_last_update
* updates the last_update of the catalog * updates the last_update of the catalog
*/ */
protected function update_last_update() { protected function update_last_update()
{
$date = time(); $date = time();
$sql = "UPDATE `catalog` SET `last_update` = ? WHERE `id` = ?"; $sql = "UPDATE `catalog` SET `last_update` = ? WHERE `id` = ?";
$db_results = Dba::write($sql, array($date, $this->id)); $db_results = Dba::write($sql, array($date, $this->id));
@ -675,8 +687,8 @@ abstract class Catalog extends database_object {
* update_last_add * update_last_add
* updates the last_add of the catalog * updates the last_add of the catalog
*/ */
public function update_last_add() { public function update_last_add()
{
$date = time(); $date = time();
$sql = "UPDATE `catalog` SET `last_add` = ? WHERE `id` = ?"; $sql = "UPDATE `catalog` SET `last_add` = ? WHERE `id` = ?";
$db_results = Dba::write($sql, array($date, $this->id)); $db_results = Dba::write($sql, array($date, $this->id));
@ -687,8 +699,8 @@ abstract class Catalog extends database_object {
* update_last_clean * update_last_clean
* This updates the last clean information * This updates the last clean information
*/ */
public function update_last_clean() { public function update_last_clean()
{
$date = time(); $date = time();
$sql = "UPDATE `catalog` SET `last_clean` = ? WHERE `id` = ?"; $sql = "UPDATE `catalog` SET `last_clean` = ? WHERE `id` = ?";
$db_results = Dba::write($sql, array($date, $this->id)); $db_results = Dba::write($sql, array($date, $this->id));
@ -699,8 +711,8 @@ abstract class Catalog extends database_object {
* update_settings * update_settings
* This function updates the basic setting of the catalog * This function updates the basic setting of the catalog
*/ */
public static function update_settings($data) { public static function update_settings($data)
{
$sql = "UPDATE `catalog` SET `name` = ?, `rename_pattern` = ?, `sort_pattern` = ? WHERE `id` = ?"; $sql = "UPDATE `catalog` SET `name` = ?, `rename_pattern` = ?, `sort_pattern` = ? WHERE `id` = ?";
$params = array($data['name'], $data['rename_pattern'], $data['sort_pattern'], $data['catalog_id']); $params = array($data['name'], $data['rename_pattern'], $data['sort_pattern'], $data['catalog_id']);
$db_results = Dba::write($sql, $params); $db_results = Dba::write($sql, $params);
@ -714,8 +726,8 @@ abstract class Catalog extends database_object {
* updates a single album,artist,song from the tag data * updates a single album,artist,song from the tag data
* this can be done by 75+ * this can be done by 75+
*/ */
public static function update_single_item($type,$id) { public static function update_single_item($type,$id)
{
// Because single items are large numbers of things too // Because single items are large numbers of things too
set_time_limit(0); set_time_limit(0);
@ -735,7 +747,7 @@ abstract class Catalog extends database_object {
break; break;
} // end switch type } // end switch type
foreach($songs as $song_id) { foreach ($songs as $song_id) {
$song = new Song($song_id); $song = new Song($song_id);
$info = self::update_media_from_tags($song,'',''); $info = self::update_media_from_tags($song,'','');
@ -764,8 +776,8 @@ abstract class Catalog extends database_object {
* This is a 'wrapper' function calls the update function for the media * This is a 'wrapper' function calls the update function for the media
* type in question * type in question
*/ */
public static function update_media_from_tags($media, $sort_pattern='', $rename_pattern='') { public static function update_media_from_tags($media, $sort_pattern='', $rename_pattern='')
{
// Check for patterns // Check for patterns
if (!$sort_pattern OR !$rename_pattern) { if (!$sort_pattern OR !$rename_pattern) {
$catalog = Catalog::create_from_id($media->catalog); $catalog = Catalog::create_from_id($media->catalog);
@ -798,8 +810,8 @@ abstract class Catalog extends database_object {
* update_video_from_tags * update_video_from_tags
* Updates the video info based on tags * Updates the video info based on tags
*/ */
public static function update_video_from_tags($results,$video) { public static function update_video_from_tags($results,$video)
{
// Pretty sweet function here // Pretty sweet function here
return $results; return $results;
@ -813,8 +825,8 @@ abstract class Catalog extends database_object {
* FIXME: This is an ugly mess, this really needs to be consolidated and * FIXME: This is an ugly mess, this really needs to be consolidated and
* cleaned up. * cleaned up.
*/ */
public static function update_song_from_tags($results,$song) { public static function update_song_from_tags($results,$song)
{
/* Setup the vars */ /* Setup the vars */
$new_song = new Song(); $new_song = new Song();
$new_song->file = $results['file']; $new_song->file = $results['file'];
@ -869,8 +881,7 @@ abstract class Catalog extends database_object {
$song->update_song($song->id,$new_song); $song->update_song($song->id,$new_song);
// Refine our reference // Refine our reference
$song = $new_song; $song = $new_song;
} } else {
else {
debug_event('update', "$song->file : no differences found", 5); debug_event('update', "$song->file : no differences found", 5);
} }
@ -883,8 +894,8 @@ abstract class Catalog extends database_object {
* *
* Cleans the catalog of files that no longer exist. * Cleans the catalog of files that no longer exist.
*/ */
public function clean_catalog() { public function clean_catalog()
{
// We don't want to run out of time // We don't want to run out of time
set_time_limit(0); set_time_limit(0);
@ -917,10 +928,10 @@ abstract class Catalog extends database_object {
* verify_catalog * verify_catalog
* This function verify the catalog * This function verify the catalog
*/ */
public function verify_catalog() { public function verify_catalog()
{
$verified = $this->verify_catalog_proc();+ $verified = $this->verify_catalog_proc();+
UI::show_box_top(); UI::show_box_top();
echo '<strong>'; echo '<strong>';
printf(T_('Catalog Verify Done. %d of %d files updated.'), $verified['updated'], $verified['total']); printf(T_('Catalog Verify Done. %d of %d files updated.'), $verified['updated'], $verified['total']);
@ -938,8 +949,8 @@ abstract class Catalog extends database_object {
* This is a wrapper function for all of the different cleaning * This is a wrapper function for all of the different cleaning
* functions, it runs them in an order that resembles correctness. * functions, it runs them in an order that resembles correctness.
*/ */
public static function gc() { public static function gc()
{
debug_event('catalog', 'Database cleanup started', 5); debug_event('catalog', 'Database cleanup started', 5);
Song::gc(); Song::gc();
Album::gc(); Album::gc();
@ -961,15 +972,15 @@ abstract class Catalog extends database_object {
* trim_prefix * trim_prefix
* Splits the prefix from the string * Splits the prefix from the string
*/ */
public static function trim_prefix($string) { public static function trim_prefix($string)
{
$prefix_pattern = '/^(' . implode('\\s|',explode('|',Config::get('catalog_prefix_pattern'))) . '\\s)(.*)/i'; $prefix_pattern = '/^(' . implode('\\s|',explode('|',Config::get('catalog_prefix_pattern'))) . '\\s)(.*)/i';
preg_match($prefix_pattern, $string, $matches); preg_match($prefix_pattern, $string, $matches);
if (count($matches)) { if (count($matches)) {
$string = trim($matches[2]); $string = trim($matches[2]);
$prefix = trim($matches[1]); $prefix = trim($matches[1]);
} } else {
else {
$prefix = null; $prefix = null;
} }
@ -982,8 +993,8 @@ abstract class Catalog extends database_object {
* set on the title, if it isn't it looks at the * set on the title, if it isn't it looks at the
* filename and trys to set the title based on that * filename and trys to set the title based on that
*/ */
public static function check_title($title,$file=0) { public static function check_title($title,$file=0)
{
if (strlen(trim($title)) < 1) { if (strlen(trim($title)) < 1) {
$title = Dba::escape($file); $title = Dba::escape($file);
} }
@ -997,8 +1008,8 @@ abstract class Catalog extends database_object {
* this takes m3u filename and then attempts to create a Public Playlist based on the filenames * this takes m3u filename and then attempts to create a Public Playlist based on the filenames
* listed in the m3u * listed in the m3u
*/ */
public static function import_m3u($filename) { public static function import_m3u($filename)
{
$m3u_handle = fopen($filename,'r'); $m3u_handle = fopen($filename,'r');
$data = fread($m3u_handle,filesize($filename)); $data = fread($m3u_handle,filesize($filename));
@ -1076,11 +1087,11 @@ abstract class Catalog extends database_object {
* Deletes the catalog and everything associated with it * Deletes the catalog and everything associated with it
* it takes the catalog id * it takes the catalog id
*/ */
public static function delete($catalog_id) { public static function delete($catalog_id)
{
// Large catalog deletion can take time // Large catalog deletion can take time
set_time_limit(0); set_time_limit(0);
// First remove the songs in this catalog // First remove the songs in this catalog
$sql = "DELETE FROM `song` WHERE `catalog` = ?"; $sql = "DELETE FROM `song` WHERE `catalog` = ?";
$db_results = Dba::write($sql, array($catalog_id)); $db_results = Dba::write($sql, array($catalog_id));
@ -1092,12 +1103,12 @@ abstract class Catalog extends database_object {
$db_results = Dba::write($sql, array($catalog_id)); $db_results = Dba::write($sql, array($catalog_id));
if (!$db_results) { return false; } if (!$db_results) { return false; }
$catalog = self::create_from_id($catalog_id); $catalog = self::create_from_id($catalog_id);
$sql = 'DELETE FROM `catalog_' . $catalog->get_type() . '` WHERE catalog_id = ?'; $sql = 'DELETE FROM `catalog_' . $catalog->get_type() . '` WHERE catalog_id = ?';
$db_results = Dba::write($sql, array($catalog_id)); $db_results = Dba::write($sql, array($catalog_id));
if (!$db_results) { return false; } if (!$db_results) { return false; }
// Next Remove the Catalog Entry it's self // Next Remove the Catalog Entry it's self
@ -1113,17 +1124,16 @@ abstract class Catalog extends database_object {
* exports the catalog * exports the catalog
* it exports all songs in the database to the given export type. * it exports all songs in the database to the given export type.
*/ */
public function export($type) { public function export($type)
{
// Select all songs in catalog // Select all songs in catalog
$params = array(); $params = array();
if($this->id) { if ($this->id) {
$sql = 'SELECT `id` FROM `song` ' . $sql = 'SELECT `id` FROM `song` ' .
"WHERE `catalog`= ? " . "WHERE `catalog`= ? " .
'ORDER BY `album`, `track`'; 'ORDER BY `album`, `track`';
$params[] = $this->id; $params[] = $this->id;
} } else {
else {
$sql = 'SELECT `id` FROM `song` ORDER BY `album`, `track`'; $sql = 'SELECT `id` FROM `song` ORDER BY `album`, `track`';
} }
$db_results = Dba::read($sql, $params); $db_results = Dba::read($sql, $params);
@ -1179,5 +1189,3 @@ abstract class Catalog extends database_object {
} // export } // export
} // end of catalog class } // end of catalog class
?>

View file

@ -33,12 +33,13 @@
* The class should be a static var in the other classes * The class should be a static var in the other classes
* *
*/ */
class Config { class Config
{
private $_local = array(); private $_local = array();
private static $_global = array(); private static $_global = array();
public function __construct() { public function __construct()
{
// Rien a faire // Rien a faire
} }
@ -47,11 +48,12 @@ class Config {
* *
* This returns a config value. * This returns a config value.
*/ */
public static function get($name) { public static function get($name)
{
if (isset(self::$_global[$name])) { if (isset(self::$_global[$name])) {
return self::$_global[$name]; return self::$_global[$name];
} }
return null; return null;
} }
@ -60,7 +62,8 @@ class Config {
* *
* This returns all of the current config variables as an array. * This returns all of the current config variables as an array.
*/ */
public static function get_all() { public static function get_all()
{
return self::$_global; return self::$_global;
} }
@ -69,13 +72,14 @@ class Config {
* *
* This sets config values. * This sets config values.
*/ */
public static function set($name, $value, $clobber = false) { public static function set($name, $value, $clobber = false)
{
if (isset(self::$_global[$name]) && !$clobber) { if (isset(self::$_global[$name]) && !$clobber) {
debug_event('Config', "Tried to overwrite existing key $name without setting clobber", 5); debug_event('Config', "Tried to overwrite existing key $name without setting clobber", 5);
Error::add('Config Global', sprintf(T_('Trying to clobber \'%s\' without setting clobber'), $name)); Error::add('Config Global', sprintf(T_('Trying to clobber \'%s\' without setting clobber'), $name));
return false; return false;
} }
self::$_global[$name] = $value; self::$_global[$name] = $value;
} }
@ -85,10 +89,10 @@ class Config {
* This is the same as the set function except it takes an array as * This is the same as the set function except it takes an array as
* input. * input.
*/ */
public static function set_by_array($array, $clobber = false) { public static function set_by_array($array, $clobber = false)
{
foreach ($array as $name => $value) { foreach ($array as $name => $value) {
self::set($name, $value, $clobber); self::set($name, $value, $clobber);
} }
} }
} }
?>

View file

@ -27,14 +27,14 @@
* would be replaced by a namespace library once that exists in php * would be replaced by a namespace library once that exists in php
* *
*/ */
class Core { class Core
{
/** /**
* constructor * constructor
* This doesn't do anything * This doesn't do anything
*/ */
private function __construct() { private function __construct()
{
return false; return false;
} // construction } // construction
@ -46,7 +46,8 @@ class Core {
* needed so that we don't use a million include statements which load * needed so that we don't use a million include statements which load
* more than we need. * more than we need.
*/ */
public static function autoload($class) { public static function autoload($class)
{
// Ignore class with namespace, not used by Ampache // Ignore class with namespace, not used by Ampache
if (strpos($class, '\\') === false) { if (strpos($class, '\\') === false) {
$file = Config::get('prefix') . '/lib/class/' . $file = Config::get('prefix') . '/lib/class/' .
@ -60,8 +61,7 @@ class Core {
if (is_callable($autocall)) { if (is_callable($autocall)) {
call_user_func($autocall); call_user_func($autocall);
} }
} } else {
else {
debug_event('autoload', "'$class' not found!", 1); debug_event('autoload', "'$class' not found!", 1);
} }
} }
@ -72,8 +72,8 @@ class Core {
* This registers a form with a SID, inserts it into the session * This registers a form with a SID, inserts it into the session
* variables and then returns a string for use in the HTML form * variables and then returns a string for use in the HTML form
*/ */
public static function form_register($name, $type = 'post') { public static function form_register($name, $type = 'post')
{
// Make ourselves a nice little sid // Make ourselves a nice little sid
$sid = md5(uniqid(rand(), true)); $sid = md5(uniqid(rand(), true));
$window = Config::get('session_length'); $window = Config::get('session_length');
@ -104,7 +104,8 @@ class Core {
* they don't match then it returns false and doesn't let the person * they don't match then it returns false and doesn't let the person
* continue * continue
*/ */
public static function form_verify($name, $type = 'post') { public static function form_verify($name, $type = 'post')
{
switch ($type) { switch ($type) {
case 'post': case 'post':
$sid = $_POST['form_validation']; $sid = $_POST['form_validation'];
@ -124,7 +125,7 @@ class Core {
debug_event('Core', "Form $sid not found in session, rejecting request", 2); debug_event('Core', "Form $sid not found in session, rejecting request", 2);
return false; return false;
} }
$form = $_SESSION['forms'][$sid]; $form = $_SESSION['forms'][$sid];
unset($_SESSION['forms'][$sid]); unset($_SESSION['forms'][$sid]);
@ -150,8 +151,8 @@ class Core {
* returns an empty array if PHP-GD is not currently installed, returns * returns an empty array if PHP-GD is not currently installed, returns
* false on error * false on error
*/ */
public static function image_dimensions($image_data) { public static function image_dimensions($image_data)
{
if (!function_exists('ImageCreateFromString')) { return false; } if (!function_exists('ImageCreateFromString')) { return false; }
$image = ImageCreateFromString($image_data); $image = ImageCreateFromString($image_data);
@ -173,7 +174,8 @@ class Core {
* Replacement function because PHP's is_readable is buggy: * Replacement function because PHP's is_readable is buggy:
* https://bugs.php.net/bug.php?id=49620 * https://bugs.php.net/bug.php?id=49620
*/ */
public static function is_readable($path) { public static function is_readable($path)
{
if (is_dir($path)) { if (is_dir($path)) {
$handle = opendir($path); $handle = opendir($path);
if ($handle === false) { if ($handle === false) {
@ -192,4 +194,3 @@ class Core {
} }
} // Core } // Core
?>

View file

@ -28,8 +28,8 @@
* 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
@ -40,8 +40,8 @@ abstract class database_object {
* 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
@ -67,7 +67,8 @@ abstract class database_object {
/** /**
* clear_cache * clear_cache
*/ */
public static function clear_cache() { public static function clear_cache()
{
self::$object_cache = array(); self::$object_cache = array();
} }
@ -75,8 +76,8 @@ 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; }
@ -88,8 +89,8 @@ 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])
@ -107,8 +108,8 @@ 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;
@ -121,8 +122,8 @@ 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]);
} }
@ -133,8 +134,8 @@ abstract class database_object {
* _auto_init * _auto_init
* Load in the cache settings once so we can avoid function calls * Load in the cache settings once so we can avoid function calls
*/ */
public static function _auto_init() { public static function _auto_init()
{
self::$_enabled = Config::get('memory_cache'); self::$_enabled = Config::get('memory_cache');
} // _auto_init } // _auto_init

View file

@ -34,8 +34,8 @@ if (!defined('INIT_LOADED') || INIT_LOADED != '1') { exit; }
* 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 $_sql; private static $_sql;
@ -46,8 +46,8 @@ class Dba {
* 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
} // construct } // construct
@ -55,7 +55,8 @@ class Dba {
/** /**
* query * query
*/ */
public static function query($sql, $params = array()) { public static function query($sql, $params = array())
{
// json_encode throws errors about UTF-8 cleanliness, which we don't // json_encode throws errors about UTF-8 cleanliness, which we don't
// care about here. // care about here.
debug_event('Query', $sql . ' ' . @json_encode($params), 6); debug_event('Query', $sql . ' ' . @json_encode($params), 6);
@ -69,7 +70,8 @@ class Dba {
return $stmt; return $stmt;
} }
private static function _query($sql, $params) { private static function _query($sql, $params)
{
$dbh = self::dbh(); $dbh = self::dbh();
if (!$dbh) { if (!$dbh) {
debug_event('Dba', 'Error: failed to get database handle', 1); debug_event('Dba', 'Error: failed to get database handle', 1);
@ -80,8 +82,7 @@ class Dba {
if ($params) { if ($params) {
$stmt = $dbh->prepare($sql); $stmt = $dbh->prepare($sql);
$stmt->execute($params); $stmt->execute($params);
} } else {
else {
$stmt = $dbh->query($sql); $stmt = $dbh->query($sql);
} }
@ -93,8 +94,7 @@ class Dba {
self::$_error = json_encode($dbh->errorInfo()); self::$_error = json_encode($dbh->errorInfo());
debug_event('Dba', 'Error: ' . json_encode($dbh->errorInfo()), 1); debug_event('Dba', 'Error: ' . json_encode($dbh->errorInfo()), 1);
self::disconnect(); self::disconnect();
} } else if ($stmt->errorCode() && $stmt->errorCode() != '00000') {
else if ($stmt->errorCode() && $stmt->errorCode() != '00000') {
self::$_error = json_encode($stmt->errorInfo()); self::$_error = json_encode($stmt->errorInfo());
debug_event('Dba', 'Error: ' . json_encode($stmt->errorInfo()), 1); debug_event('Dba', 'Error: ' . json_encode($stmt->errorInfo()), 1);
self::disconnect(); self::disconnect();
@ -107,14 +107,16 @@ class Dba {
/** /**
* read * read
*/ */
public static function read($sql, $params = null) { public static function read($sql, $params = null)
{
return self::query($sql, $params); return self::query($sql, $params);
} }
/** /**
* write * write
*/ */
public static function write($sql, $params = null) { public static function write($sql, $params = null)
{
return self::query($sql, $params); return self::query($sql, $params);
} }
@ -124,7 +126,8 @@ class Dba {
* 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)
{
$var = self::dbh()->quote($var); $var = self::dbh()->quote($var);
// This is slightly less ugly than it was, but still ugly // This is slightly less ugly than it was, but still ugly
return substr($var, 1, -1); return substr($var, 1, -1);
@ -138,7 +141,8 @@ class Dba {
* The optional finish parameter affects whether we automatically clean * The optional finish parameter affects whether we automatically clean
* up the result set after the last row is read. * up the result set after the last row is read.
*/ */
public static function fetch_assoc($resource, $finish = true) { public static function fetch_assoc($resource, $finish = true)
{
if (!$resource) { if (!$resource) {
return array(); return array();
} }
@ -163,7 +167,8 @@ class Dba {
* The optional finish parameter affects whether we automatically clean * The optional finish parameter affects whether we automatically clean
* up the result set after the last row is read. * up the result set after the last row is read.
*/ */
public static function fetch_row($resource, $finish = true) { public static function fetch_row($resource, $finish = true)
{
if (!$resource) { if (!$resource) {
return array(); return array();
} }
@ -187,7 +192,8 @@ 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)
{
if ($resource) { if ($resource) {
$result = $resource->rowCount(); $result = $resource->rowCount();
if ($result) { if ($result) {
@ -203,7 +209,8 @@ class Dba {
* *
* This closes a result handle and clears the memory associated with it * This closes a result handle and clears the memory associated with it
*/ */
public static function finish($resource) { public static function finish($resource)
{
if ($resource) { if ($resource) {
$resource->closeCursor(); $resource->closeCursor();
} }
@ -214,7 +221,8 @@ class Dba {
* *
* 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)
{
if ($resource) { if ($resource) {
$result = $resource->rowCount(); $result = $resource->rowCount();
if ($result) { if ($result) {
@ -230,7 +238,8 @@ class Dba {
* *
* This connects to the database, used by the DBH function * This connects to the database, used by the DBH function
*/ */
private static function _connect() { private static function _connect()
{
$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');
@ -239,8 +248,7 @@ class Dba {
// Build the data source name // Build the data source name
if (strpos($hostname, '/') === 0) { if (strpos($hostname, '/') === 0) {
$dsn = 'mysql:unix_socket=' . $hostname; $dsn = 'mysql:unix_socket=' . $hostname;
} } else {
else {
$dsn = 'mysql:host=' . $hostname ?: 'localhost'; $dsn = 'mysql:host=' . $hostname ?: 'localhost';
} }
if ($port) { if ($port) {
@ -249,8 +257,7 @@ class Dba {
try { try {
$dbh = new PDO($dsn, $username, $password); $dbh = new PDO($dsn, $username, $password);
} } catch (PDOException $e) {
catch (PDOException $e) {
self::$_error = $e->getMessage(); self::$_error = $e->getMessage();
debug_event('Dba', 'Connection failed: ' . $e->getMessage(), 1); debug_event('Dba', 'Connection failed: ' . $e->getMessage(), 1);
return null; return null;
@ -259,7 +266,8 @@ class Dba {
return $dbh; return $dbh;
} }
private static function _setup_dbh($dbh, $database) { private static function _setup_dbh($dbh, $database)
{
if (!$dbh) { if (!$dbh) {
return false; return false;
} }
@ -287,7 +295,8 @@ class Dba {
* *
* Make sure that we can connect to the database * Make sure that we can connect to the database
*/ */
public static function check_database() { public static function check_database()
{
$dbh = self::_connect(); $dbh = self::_connect();
if (!$dbh || $dbh->errorCode()) { if (!$dbh || $dbh->errorCode()) {
@ -306,7 +315,8 @@ class Dba {
* Checks to make sure that you have inserted the database * Checks to make sure that you have inserted the database
* and that the user you are using has access to it. * and that the user you are using has access to it.
*/ */
public static function check_database_inserted() { public static function check_database_inserted()
{
$sql = "DESCRIBE session"; $sql = "DESCRIBE session";
$db_results = Dba::read($sql); $db_results = Dba::read($sql);
@ -327,7 +337,8 @@ class Dba {
* *
* This function is used for debug, helps with profiling * This function is used for debug, helps with profiling
*/ */
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::read('SHOW PROFILES'); $res = Dba::read('SHOW PROFILES');
@ -345,7 +356,8 @@ 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) { if (!$database) {
$database = Config::get('database_name'); $database = Config::get('database_name');
} }
@ -358,8 +370,7 @@ class Dba {
self::_setup_dbh($dbh, $database); self::_setup_dbh($dbh, $database);
Config::set($handle, $dbh, true); Config::set($handle, $dbh, true);
return $dbh; return $dbh;
} } else {
else {
return Config::get($handle); return Config::get($handle);
} }
} }
@ -369,9 +380,10 @@ class Dba {
* *
* This nukes the dbh connection, this isn't used very often... * This nukes the dbh connection, this isn't used very often...
*/ */
public static function disconnect($database = '') { public static function disconnect($database = '')
{
if (!$database) { if (!$database) {
$database = Config::get('database_name'); $database = Config::get('database_name');
} }
$handle = 'dbh_' . $database; $handle = 'dbh_' . $database;
@ -385,7 +397,8 @@ class Dba {
/** /**
* insert_id * insert_id
*/ */
public static function insert_id() { public static function insert_id()
{
$dbh = self::dbh(); $dbh = self::dbh();
if ($dbh) { if ($dbh) {
return $dbh->lastInsertId(); return $dbh->lastInsertId();
@ -397,7 +410,8 @@ 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 self::$_error; return self::$_error;
} }
@ -406,7 +420,8 @@ class Dba {
* *
* This translates the specified charset to a mysql charset. * This translates the specified charset to a mysql charset.
*/ */
public static function translate_to_mysqlcharset($charset) { public static function translate_to_mysqlcharset($charset)
{
// Translate real charset names into fancy MySQL land names // Translate real charset names into fancy MySQL land names
switch (strtoupper($charset)) { switch (strtoupper($charset)) {
case 'CP1250': case 'CP1250':
@ -462,7 +477,8 @@ class Dba {
* administrator only. This can mess up data if you switch between charsets * administrator only. This can mess up data if you switch between charsets
* that are not overlapping. * that are not overlapping.
*/ */
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'];
@ -496,7 +512,7 @@ class Dba {
} // if it fails } // if it fails
} }
} }
} }
} }
/** /**
@ -504,15 +520,16 @@ class Dba {
* *
* This runs an optimize on the tables and updates the stats to improve * This runs an optimize on the tables and updates the stats to improve
* join speed. * join speed.
* This can be slow, but is a good idea to do from time to time. We do * This can be slow, but is a good idea to do from time to time. We do
* it in case the dba isn't doing it... which we're going to assume they * it in case the dba isn't doing it... which we're going to assume they
* aren't. * aren't.
*/ */
public static function optimize_tables() { public static function optimize_tables()
{
$sql = "SHOW TABLES"; $sql = "SHOW TABLES";
$db_results = Dba::read($sql); $db_results = Dba::read($sql);
while($row = Dba::fetch_row($db_results)) { while ($row = Dba::fetch_row($db_results)) {
$sql = "OPTIMIZE TABLE `" . $row[0] . "`"; $sql = "OPTIMIZE TABLE `" . $row[0] . "`";
$db_results_inner = Dba::write($sql); $db_results_inner = Dba::write($sql);
@ -521,4 +538,3 @@ class Dba {
} }
} }
} }
?>

View file

@ -27,8 +27,8 @@
* name for voting based playback. * name for voting based playback.
* *
*/ */
class Democratic extends Tmp_Playlist { class Democratic extends Tmp_Playlist
{
public $name; public $name;
public $cooldown; public $cooldown;
public $level; public $level;
@ -46,8 +46,8 @@ class Democratic extends Tmp_Playlist {
* constructor * constructor
* We need a constructor for this class. It does it's own thing now * We need a constructor for this class. It does it's own thing now
*/ */
public function __construct($id='') { public function __construct($id='')
{
if (!$id) { return false; } if (!$id) { return false; }
$info = $this->get_info($id); $info = $this->get_info($id);
@ -62,8 +62,8 @@ class Democratic extends Tmp_Playlist {
* build_vote_cache * build_vote_cache
* This builds a vote cache of the objects we've got in the playlist * This builds a vote cache of the objects we've got in the playlist
*/ */
public static function build_vote_cache($ids) { public static function build_vote_cache($ids)
{
if (!is_array($ids) || !count($ids)) { return false; } if (!is_array($ids) || !count($ids)) { return false; }
$idlist = '(' . implode(',', $ids) . ')'; $idlist = '(' . implode(',', $ids) . ')';
@ -87,8 +87,8 @@ class Democratic extends Tmp_Playlist {
* This function just returns true / false if the current democratic * This function just returns true / false if the current democratic
* playlist is currently enabled / configured * playlist is currently enabled / configured
*/ */
public function is_enabled() { public function is_enabled()
{
if ($this->tmp_playlist) { return true; } if ($this->tmp_playlist) { return true; }
return false; return false;
@ -99,8 +99,8 @@ class Democratic extends Tmp_Playlist {
* set_parent * set_parent
* This returns the Tmp_Playlist for this democratic play instance * This returns the Tmp_Playlist for this democratic play instance
*/ */
public function set_parent() { public function set_parent()
{
$demo_id = Dba::escape($this->id); $demo_id = Dba::escape($this->id);
$sql = "SELECT * FROM `tmp_playlist` WHERE `session`='$demo_id'"; $sql = "SELECT * FROM `tmp_playlist` WHERE `session`='$demo_id'";
@ -120,8 +120,8 @@ class Democratic extends Tmp_Playlist {
* passed it does it for everyone and also locks down the ability to * passed it does it for everyone and also locks down the ability to
* change to admins only * change to admins only
*/ */
public static function set_user_preferences($user = null) { public static function set_user_preferences($user = null)
{
//FIXME: Code in single user stuff //FIXME: Code in single user stuff
$preference_id = Preference::id_from_name('play_type'); $preference_id = Preference::id_from_name('play_type');
@ -142,8 +142,8 @@ class Democratic extends Tmp_Playlist {
* format * format
* This makes the variables all purrty so that they can be displayed * This makes the variables all purrty so that they can be displayed
*/ */
public function format() { public function format()
{
$this->f_cooldown = $this->cooldown . ' ' . T_('minutes'); $this->f_cooldown = $this->cooldown . ' ' . T_('minutes');
$this->f_primary = $this->primary ? T_('Primary') : ''; $this->f_primary = $this->primary ? T_('Primary') : '';
@ -172,8 +172,8 @@ class Democratic extends Tmp_Playlist {
* This returns all of the current valid 'Democratic' Playlists * This returns all of the current valid 'Democratic' Playlists
* that have been created. * that have been created.
*/ */
public static function get_playlists() { public static function get_playlists()
{
$sql = "SELECT `id` FROM `democratic` ORDER BY `name`"; $sql = "SELECT `id` FROM `democratic` ORDER BY `name`";
$db_results = Dba::read($sql); $db_results = Dba::read($sql);
@ -192,8 +192,8 @@ class Democratic extends Tmp_Playlist {
* This returns the curren users current playlist, or if specified * This returns the curren users current playlist, or if specified
* this current playlist of the user * this current playlist of the user
*/ */
public static function get_current_playlist() { public static function get_current_playlist()
{
$democratic_id = Config::get('democratic_id'); $democratic_id = Config::get('democratic_id');
if (!$democratic_id) { if (!$democratic_id) {
@ -217,11 +217,11 @@ class Democratic extends Tmp_Playlist {
* The array is multidimensional; the inner array needs to contain the * The array is multidimensional; the inner array needs to contain the
* keys 'id', 'object_type' and 'object_id'. * keys 'id', 'object_type' and 'object_id'.
* *
* Sorting is highest to lowest vote count, then by oldest to newest * Sorting is highest to lowest vote count, then by oldest to newest
* vote activity. * vote activity.
*/ */
public function get_items($limit = null) { public function get_items($limit = null)
{
$sql = 'SELECT `tmp_playlist_data`.`object_type`, ' . $sql = 'SELECT `tmp_playlist_data`.`object_type`, ' .
'`tmp_playlist_data`.`object_id`, ' . '`tmp_playlist_data`.`object_id`, ' .
'`tmp_playlist_data`.`id` ' . '`tmp_playlist_data`.`id` ' .
@ -230,8 +230,8 @@ class Democratic extends Tmp_Playlist {
"WHERE `tmp_playlist_data`.`tmp_playlist` = '" . "WHERE `tmp_playlist_data`.`tmp_playlist` = '" .
Dba::escape($this->tmp_playlist) . "' " . Dba::escape($this->tmp_playlist) . "' " .
'GROUP BY 1, 2 ' . 'GROUP BY 1, 2 ' .
'ORDER BY COUNT(*) DESC, MAX(`user_vote`.`date`) '; 'ORDER BY COUNT(*) DESC, MAX(`user_vote`.`date`) ';
if ($limit) { if ($limit) {
$sql .= 'LIMIT ' . intval($limit); $sql .= 'LIMIT ' . intval($limit);
} }
@ -254,8 +254,8 @@ class Democratic extends Tmp_Playlist {
* play_url * play_url
* This returns the special play URL for democratic play, only open to ADMINs * This returns the special play URL for democratic play, only open to ADMINs
*/ */
public function play_url() { public function play_url()
{
$link = Stream::get_base_url() . 'uid=' . scrub_out($GLOBALS['user']->id) . '&demo_id=' . scrub_out($this->id); $link = Stream::get_base_url() . 'uid=' . scrub_out($GLOBALS['user']->id) . '&demo_id=' . scrub_out($this->id);
return $link; return $link;
@ -269,8 +269,8 @@ class Democratic extends Tmp_Playlist {
* base_playlist and no items in the playlist then it returns a random * base_playlist and no items in the playlist then it returns a random
* entry from the base_playlist * entry from the base_playlist
*/ */
public function get_next_object($offset = 0) { public function get_next_object($offset = 0)
{
// FIXME: Shouldn't this return object_type? // FIXME: Shouldn't this return object_type?
$offset = intval($offset); $offset = intval($offset);
@ -288,8 +288,7 @@ class Democratic extends Tmp_Playlist {
$base_playlist = new Playlist($this->base_playlist); $base_playlist = new Playlist($this->base_playlist);
$data = $base_playlist->get_random_items(1); $data = $base_playlist->get_random_items(1);
return $data[0]['object_id']; return $data[0]['object_id'];
} } else {
else {
$sql = "SELECT `id` FROM `song` WHERE `enabled`='1' ORDER BY RAND() LIMIT 1"; $sql = "SELECT `id` FROM `song` WHERE `enabled`='1' ORDER BY RAND() LIMIT 1";
$db_results = Dba::read($sql); $db_results = Dba::read($sql);
$results = Dba::fetch_assoc($db_results); $results = Dba::fetch_assoc($db_results);
@ -304,8 +303,8 @@ class Democratic extends Tmp_Playlist {
* get_uid_from_object_id * get_uid_from_object_id
* This takes an object_id and an object type and returns the ID for the row * This takes an object_id and an object type and returns the ID for the row
*/ */
public function get_uid_from_object_id($object_id, $object_type = 'song') { public function get_uid_from_object_id($object_id, $object_type = 'song')
{
$object_id = Dba::escape($object_id); $object_id = Dba::escape($object_id);
$object_type = Dba::escape($object_type); $object_type = Dba::escape($object_type);
$tmp_id = Dba::escape($this->tmp_playlist); $tmp_id = Dba::escape($this->tmp_playlist);
@ -326,8 +325,8 @@ class Democratic extends Tmp_Playlist {
* This returns all of the song_ids for songs that have happened within * This returns all of the song_ids for songs that have happened within
* the last 'cooldown' for this user. * the last 'cooldown' for this user.
*/ */
public function get_cool_songs() { public function get_cool_songs()
{
// Convert cooldown time to a timestamp in the past // Convert cooldown time to a timestamp in the past
$cool_time = time() - ($this->cooldown * 60); $cool_time = time() - ($this->cooldown * 60);
@ -344,7 +343,8 @@ class Democratic extends Tmp_Playlist {
* by this user, naturally it checks to make sure that the user hasn't * by this user, naturally it checks to make sure that the user hasn't
* already voted on any of these objects * already voted on any of these objects
*/ */
public function add_vote($items) { public function add_vote($items)
{
/* Iterate through the objects if no vote, add to playlist and vote */ /* Iterate through the objects if no vote, add to playlist and vote */
foreach ($items as $element) { foreach ($items as $element) {
$type = array_shift($element); $type = array_shift($element);
@ -360,8 +360,8 @@ class Democratic extends Tmp_Playlist {
* has_vote * has_vote
* This checks to see if the current user has already voted on this object * This checks to see if the current user has already voted on this object
*/ */
public function has_vote($object_id, $type = 'song') { public function has_vote($object_id, $type = 'song')
{
$tmp_id = Dba::escape($this->tmp_playlist); $tmp_id = Dba::escape($this->tmp_playlist);
$object_id = Dba::escape($object_id); $object_id = Dba::escape($object_id);
$type = Dba::escape($type); $type = Dba::escape($type);
@ -390,8 +390,8 @@ class Democratic extends Tmp_Playlist {
* _add_vote * _add_vote
* This takes a object id and user and actually inserts the row * This takes a object id and user and actually inserts the row
*/ */
private function _add_vote($object_id, $object_type = 'song') { private function _add_vote($object_id, $object_type = 'song')
{
$object_id = Dba::escape($object_id); $object_id = Dba::escape($object_id);
$tmp_playlist = Dba::escape($this->tmp_playlist); $tmp_playlist = Dba::escape($this->tmp_playlist);
$object_type = Dba::escape($object_type); $object_type = Dba::escape($object_type);
@ -426,8 +426,8 @@ class Democratic extends Tmp_Playlist {
* As that's what we'll have most the time, no need to check if they've got an existing * As that's what we'll have most the time, no need to check if they've got an existing
* vote for this, just remove anything that is there * vote for this, just remove anything that is there
*/ */
public function remove_vote($row_id) { public function remove_vote($row_id)
{
$object_id = Dba::escape($row_id); $object_id = Dba::escape($row_id);
$user_id = Dba::escape($GLOBALS['user']->id); $user_id = Dba::escape($GLOBALS['user']->id);
@ -445,8 +445,8 @@ class Democratic extends Tmp_Playlist {
* delete_votes * delete_votes
* This removes the votes for the specified object on the current playlist * This removes the votes for the specified object on the current playlist
*/ */
public function delete_votes($row_id) { public function delete_votes($row_id)
{
$row_id = Dba::escape($row_id); $row_id = Dba::escape($row_id);
$sql = "DELETE FROM `user_vote` WHERE `object_id`='$row_id'"; $sql = "DELETE FROM `user_vote` WHERE `object_id`='$row_id'";
@ -463,25 +463,24 @@ class Democratic extends Tmp_Playlist {
* delete_from_oid * delete_from_oid
* This takes an OID and type and removes the object from the democratic playlist * This takes an OID and type and removes the object from the democratic playlist
*/ */
public function delete_from_oid($oid,$object_type) { public function delete_from_oid($oid,$object_type)
{
$row_id = $this->get_uid_from_object_id($oid,$object_type); $row_id = $this->get_uid_from_object_id($oid,$object_type);
if ($row_id) { if ($row_id) {
debug_event('Democratic','Removing Votes for ' . $oid . ' of type ' . $object_type,'5'); debug_event('Democratic','Removing Votes for ' . $oid . ' of type ' . $object_type,'5');
$this->delete_votes($row_id); $this->delete_votes($row_id);
} } else { debug_event('Democratic','Unable to find Votes for ' . $oid . ' of type ' . $object_type,'3'); }
else { debug_event('Democratic','Unable to find Votes for ' . $oid . ' of type ' . $object_type,'3'); }
return true; return true;
} // delete_from_oid } // delete_from_oid
/** /**
* delete * delete
* This deletes a democratic playlist * This deletes a democratic playlist
*/ */
public static function delete($democratic_id) { public static function delete($democratic_id)
{
$democratic_id = Dba::escape($democratic_id); $democratic_id = Dba::escape($democratic_id);
$sql = "DELETE FROM `democratic` WHERE `id`='$democratic_id'"; $sql = "DELETE FROM `democratic` WHERE `id`='$democratic_id'";
@ -500,8 +499,8 @@ class Democratic extends Tmp_Playlist {
* update * update
* This updates an existing democratic playlist item. It takes a key'd array just like the create * This updates an existing democratic playlist item. It takes a key'd array just like the create
*/ */
public function update($data) { public function update($data)
{
$name = Dba::escape($data['name']); $name = Dba::escape($data['name']);
$base = Dba::escape($data['democratic']); $base = Dba::escape($data['democratic']);
$cool = Dba::escape($data['cooldown']); $cool = Dba::escape($data['cooldown']);
@ -518,8 +517,8 @@ class Democratic extends Tmp_Playlist {
* create * create
* This is the democratic play create function it inserts this into the democratic table * This is the democratic play create function it inserts this into the democratic table
*/ */
public static function create($data) { public static function create($data)
{
// Clean up the input // Clean up the input
$name = Dba::escape($data['name']); $name = Dba::escape($data['name']);
$base = Dba::escape($data['democratic']); $base = Dba::escape($data['democratic']);
@ -550,8 +549,8 @@ class Democratic extends Tmp_Playlist {
* This replaces the normal prune tracks and correctly removes the votes * This replaces the normal prune tracks and correctly removes the votes
* as well * as well
*/ */
public static function prune_tracks() { public static function prune_tracks()
{
// This deletes data without votes, if it's a voting democratic playlist // This deletes data without votes, if it's a voting democratic playlist
$sql = "DELETE FROM `tmp_playlist_data` USING `tmp_playlist_data` " . $sql = "DELETE FROM `tmp_playlist_data` USING `tmp_playlist_data` " .
"LEFT JOIN `user_vote` ON `tmp_playlist_data`.`id`=`user_vote`.`object_id` " . "LEFT JOIN `user_vote` ON `tmp_playlist_data`.`id`=`user_vote`.`object_id` " .
@ -568,8 +567,8 @@ class Democratic extends Tmp_Playlist {
* This is really just a wrapper function, it clears the entire playlist * This is really just a wrapper function, it clears the entire playlist
* including all votes etc. * including all votes etc.
*/ */
public function clear() { public function clear()
{
$tmp_id = Dba::escape($this->tmp_playlist); $tmp_id = Dba::escape($this->tmp_playlist);
/* Clear all votes then prune */ /* Clear all votes then prune */
@ -592,8 +591,8 @@ class Democratic extends Tmp_Playlist {
* clean_votes * clean_votes
* This removes in left over garbage in the votes table * This removes in left over garbage in the votes table
*/ */
public function clear_votes() { public function clear_votes()
{
$sql = "DELETE FROM `user_vote` USING `user_vote` " . $sql = "DELETE FROM `user_vote` USING `user_vote` " .
"LEFT JOIN `tmp_playlist_data` ON `user_vote`.`object_id`=`tmp_playlist_data`.`id` " . "LEFT JOIN `tmp_playlist_data` ON `user_vote`.`object_id`=`tmp_playlist_data`.`id` " .
"WHERE `tmp_playlist_data`.`id` IS NULL"; "WHERE `tmp_playlist_data`.`id` IS NULL";
@ -607,8 +606,8 @@ class Democratic extends Tmp_Playlist {
* get_vote * get_vote
* This returns the current count for a specific song * This returns the current count for a specific song
*/ */
public function get_vote($id) { public function get_vote($id)
{
if (parent::is_cached('democratic_vote', $id)) { if (parent::is_cached('democratic_vote', $id)) {
return parent::get_from_cache('democratic_vote', $id); return parent::get_from_cache('democratic_vote', $id);
} }
@ -628,12 +627,11 @@ class Democratic extends Tmp_Playlist {
* This returns the users that voted for the specified object * This returns the users that voted for the specified object
* This is an array of user ids * This is an array of user ids
*/ */
public function get_voters($object_id) { public function get_voters($object_id)
{
return parent::get_from_cache('democratic_voters',$object_id); return parent::get_from_cache('democratic_voters',$object_id);
} // get_voters } // get_voters
} // Democratic class } // Democratic class
?>

View file

@ -27,8 +27,8 @@
* hello static functions and variables * hello static functions and variables
* *
*/ */
class Error { class Error
{
private static $state = false; // set to one when an error occurs private static $state = false; // set to one when an error occurs
private static $errors = array(); // Errors array key'd array with errors that have occured private static $errors = array(); // Errors array key'd array with errors that have occured
@ -36,8 +36,8 @@ class Error {
* __constructor * __constructor
* This does nothing... amazing isn't it! * This does nothing... amazing isn't it!
*/ */
private function __construct() { private function __construct()
{
// Rien a faire // Rien a faire
} // __construct } // __construct
@ -46,9 +46,8 @@ class Error {
* __destruct * __destruct
* This saves all of the errors that are left into the session * This saves all of the errors that are left into the session
*/ */
public function __destruct() { public function __destruct()
{
foreach (self::$errors as $key=>$error) { foreach (self::$errors as $key=>$error) {
$_SESSION['errors'][$key] = $error; $_SESSION['errors'][$key] = $error;
} }
@ -60,8 +59,8 @@ class Error {
* This is a public static function it adds a new error message to the array * This is a public static function it adds a new error message to the array
* It can optionally clobber rather then adding to the error message * It can optionally clobber rather then adding to the error message
*/ */
public static function add($name,$message,$clobber=0) { public static function add($name,$message,$clobber=0)
{
// Make sure its set first // Make sure its set first
if (!isset(Error::$errors[$name])) { if (!isset(Error::$errors[$name])) {
Error::$errors[$name] = $message; Error::$errors[$name] = $message;
@ -87,8 +86,8 @@ class Error {
* occurred * occurred
* This returns true / false if an error has occured anywhere * This returns true / false if an error has occured anywhere
*/ */
public static function occurred() { public static function occurred()
{
if (self::$state == '1') { return true; } if (self::$state == '1') { return true; }
return false; return false;
@ -99,8 +98,8 @@ class Error {
* get * get
* This returns an error by name * This returns an error by name
*/ */
public static function get($name) { public static function get($name)
{
if (!isset(Error::$errors[$name])) { return ''; } if (!isset(Error::$errors[$name])) { return ''; }
return Error::$errors[$name]; return Error::$errors[$name];
@ -112,8 +111,8 @@ class Error {
* This prints the error out with a standard Error class span * This prints the error out with a standard Error class span
* Ben Goska: Renamed from print to display, print is reserved * Ben Goska: Renamed from print to display, print is reserved
*/ */
public static function display($name) { public static function display($name)
{
// Be smart about this, if no error don't print // Be smart about this, if no error don't print
if (!isset(Error::$errors[$name])) { return ''; } if (!isset(Error::$errors[$name])) { return ''; }
@ -125,8 +124,8 @@ class Error {
* auto_init * auto_init
* This loads the errors from the session back into Ampache * This loads the errors from the session back into Ampache
*/ */
public static function auto_init() { public static function auto_init()
{
if (!is_array($_SESSION['errors'])) { return false; } if (!is_array($_SESSION['errors'])) { return false; }
// Re-insert them // Re-insert them

View file

@ -27,8 +27,8 @@
* This handles flagging of songs, albums and artists * This handles flagging of songs, albums and artists
* *
*/ */
class Flag extends database_object { class Flag extends database_object
{
public $id; public $id;
public $user; public $user;
public $object_id; public $object_id;
@ -46,8 +46,8 @@ class Flag extends database_object {
* Constructor * Constructor
* This takes a flagged.id and then pulls in the information for said flag entry * This takes a flagged.id and then pulls in the information for said flag entry
*/ */
public function __construct($flag_id) { public function __construct($flag_id)
{
$info = $this->get_info($flag_id,'flagged'); $info = $this->get_info($flag_id,'flagged');
foreach ($info as $key=>$value) { foreach ($info as $key=>$value) {
@ -63,7 +63,8 @@ class Flag extends database_object {
* *
* This cleans out unused flagged items * This cleans out unused flagged items
*/ */
public static function gc() { public static function gc()
{
Dba::write("DELETE FROM `flagged` USING `flagged` LEFT JOIN `song` ON `song`.`id` = `flagged`.`object_id` WHERE `song`.`id` IS NULL AND `object_type` = 'song'"); Dba::write("DELETE FROM `flagged` USING `flagged` LEFT JOIN `song` ON `song`.`id` = `flagged`.`object_id` WHERE `song`.`id` IS NULL AND `object_type` = 'song'");
} }
@ -72,8 +73,8 @@ class Flag extends database_object {
* This takes an array of ids and builds up a nice little cache * This takes an array of ids and builds up a nice little cache
* for us * for us
*/ */
public static function build_cache($ids) { public static function build_cache($ids)
{
if (!is_array($ids) OR !count($ids)) { return false; } if (!is_array($ids) OR !count($ids)) { return false; }
$idlist = '(' . implode(',',$ids) . ')'; $idlist = '(' . implode(',',$ids) . ')';
@ -92,8 +93,8 @@ class Flag extends database_object {
* This takes an array of ids and builds a map cache to avoid some of the object_type calls * This takes an array of ids and builds a map cache to avoid some of the object_type calls
* we would normally have to make * we would normally have to make
*/ */
public static function build_map_cache($ids,$type) { public static function build_map_cache($ids,$type)
{
if (!is_array($ids) OR !count($ids)) { return false; } if (!is_array($ids) OR !count($ids)) { return false; }
$idlist = '(' . implode(',',$ids) . ')'; $idlist = '(' . implode(',',$ids) . ')';
@ -120,8 +121,8 @@ class Flag extends database_object {
* has_flag * has_flag
* Static function, tries to check the cache, but falls back on a query * Static function, tries to check the cache, but falls back on a query
*/ */
public static function has_flag($id,$type) { public static function has_flag($id,$type)
{
if (parent::is_cached('flagged_' . $type,$id)) { if (parent::is_cached('flagged_' . $type,$id)) {
$data = parent::get_from_cache('flagged_' . $type,$id); $data = parent::get_from_cache('flagged_' . $type,$id);
return $data['date']; return $data['date'];
@ -145,8 +146,8 @@ class Flag extends database_object {
* This returns the id's of the most recently flagged songs, it takes an int * This returns the id's of the most recently flagged songs, it takes an int
* as an argument which is the count of the object you want to return * as an argument which is the count of the object you want to return
*/ */
public static function get_recent($count=0) { public static function get_recent($count=0)
{
if ($count) { $limit = " LIMIT " . intval($count); } if ($count) { $limit = " LIMIT " . intval($count); }
$results = array(); $results = array();
@ -167,8 +168,8 @@ class Flag extends database_object {
* This returns all of the songs that have been disabled, this is * This returns all of the songs that have been disabled, this is
* a form of being flagged * a form of being flagged
*/ */
public static function get_disabled() { public static function get_disabled()
{
$sql = "SELECT `id` FROM `song` WHERE `enabled`='0'"; $sql = "SELECT `id` FROM `song` WHERE `enabled`='0'";
$db_results = Dba::read($sql); $db_results = Dba::read($sql);
@ -187,8 +188,8 @@ class Flag extends database_object {
* This returns an array of ids of flagged songs if no limit is passed * This returns an array of ids of flagged songs if no limit is passed
* it gets everything * it gets everything
*/ */
public static function get_all($count=0) { public static function get_all($count=0)
{
if ($count) { $limit_clause = "LIMIT " . intval($count); } if ($count) { $limit_clause = "LIMIT " . intval($count); }
$sql = "SELECT `id` FROM `flagged` $limit_clause"; $sql = "SELECT `id` FROM `flagged` $limit_clause";
@ -210,8 +211,8 @@ class Flag extends database_object {
* get_approved * get_approved
* This returns an array of approved flagged songs * This returns an array of approved flagged songs
*/ */
public static function get_approved() { public static function get_approved()
{
$sql = "SELECT `id` FROM `flagged` WHERE `approved`='1'"; $sql = "SELECT `id` FROM `flagged` WHERE `approved`='1'";
$db_results = Dba::read($sql); $db_results = Dba::read($sql);
@ -233,8 +234,8 @@ class Flag extends database_object {
* This adds a flag entry for an item, it takes an id, a type, the flag type * This adds a flag entry for an item, it takes an id, a type, the flag type
* and a comment and then inserts the mofo * and a comment and then inserts the mofo
*/ */
public static function add($id,$type,$flag,$comment) { public static function add($id,$type,$flag,$comment)
{
$id = Dba::escape($id); $id = Dba::escape($id);
$type = Dba::escape($type); $type = Dba::escape($type);
$flag = self::validate_flag($flag); $flag = self::validate_flag($flag);
@ -260,8 +261,8 @@ class Flag extends database_object {
* state, in a perfect world, I could just roll the changes back... not until 3.4 * state, in a perfect world, I could just roll the changes back... not until 3.4
* or.. haha 3.5! * or.. haha 3.5!
*/ */
public function delete() { public function delete()
{
// Re-scan the file // Re-scan the file
$song = new Song($this->object_id); $song = new Song($this->object_id);
$info = Catalog::update_media_from_tags($song); $info = Catalog::update_media_from_tags($song);
@ -282,8 +283,8 @@ class Flag extends database_object {
* This approves the current flag object ($this->id) by setting approved to * This approves the current flag object ($this->id) by setting approved to
* 1 * 1
*/ */
public function approve() { public function approve()
{
$sql = "UPDATE `flagged` SET `approved`='1' WHERE `id`='$this->id'"; $sql = "UPDATE `flagged` SET `approved`='1' WHERE `id`='$this->id'";
$db_results = Dba::write($sql); $db_results = Dba::write($sql);
@ -298,8 +299,8 @@ class Flag extends database_object {
* This function figures out what kind of object we've got and sets up all the * This function figures out what kind of object we've got and sets up all the
* vars all nice and fuzzy like * vars all nice and fuzzy like
*/ */
public function format() { public function format()
{
switch ($this->object_type) { switch ($this->object_type) {
case 'song': case 'song':
$song = new Song($this->object_id); $song = new Song($this->object_id);
@ -319,10 +320,9 @@ class Flag extends database_object {
* This prints out a userfriendly version of the current status for this flagged * This prints out a userfriendly version of the current status for this flagged
* object * object
*/ */
public function print_status() { public function print_status()
{
if ($this->approved) { echo T_('Approved'); } if ($this->approved) { echo T_('Approved'); } else { echo T_('Pending'); }
else { echo T_('Pending'); }
} // print_status } // print_status
@ -330,8 +330,8 @@ class Flag extends database_object {
* print_flag * print_flag
* This prints out a userfriendly version of the current flag type * This prints out a userfriendly version of the current flag type
*/ */
public function print_flag() { public function print_flag()
{
switch ($this->flag) { switch ($this->flag) {
case 'delete': case 'delete':
$name = T_('Delete'); $name = T_('Delete');
@ -359,8 +359,8 @@ class Flag extends database_object {
* This takes a flag input and makes sure it's one of the reigstered * This takes a flag input and makes sure it's one of the reigstered
* and valid 'flag' values * and valid 'flag' values
*/ */
public static function validate_flag($flag) { public static function validate_flag($flag)
{
switch ($flag) { switch ($flag) {
case 'delete': case 'delete':
case 'retag': case 'retag':
@ -379,8 +379,8 @@ class Flag extends database_object {
* fill_tags * fill_tags
* This is used by the write_tags script. * This is used by the write_tags script.
*/ */
public static function fill_tags( $tagWriter, $song, $type = 'comment' ) { public static function fill_tags( $tagWriter, $song, $type = 'comment' )
{
// Set all of the attributes for the tag to be written(All pulled from the song object) // Set all of the attributes for the tag to be written(All pulled from the song object)
// Use a function since ID3v1, ID3v2, and vorbis/flac/ape are different // Use a function since ID3v1, ID3v2, and vorbis/flac/ape are different
switch ($type) { switch ($type) {
@ -422,5 +422,3 @@ class Flag extends database_object {
} //end of flag class } //end of flag class
?>

View file

@ -20,8 +20,8 @@
* *
*/ */
class Localplay { class Localplay
{
/* Base Variables */ /* Base Variables */
public $type; public $type;
@ -36,8 +36,8 @@ class Localplay {
* file for the specified type and attempts to load in the function * file for the specified type and attempts to load in the function
* map, the preferences and the template * map, the preferences and the template
*/ */
public function __construct($type) { public function __construct($type)
{
$this->type = $type; $this->type = $type;
$this->_get_info(); $this->_get_info();
@ -51,8 +51,8 @@ class Localplay {
* any failures, fatal errors will actually return something to the * any failures, fatal errors will actually return something to the
* gui * gui
*/ */
private function _get_info() { private function _get_info()
{
$this->_load_player(); $this->_load_player();
} // _get_info } // _get_info
@ -62,12 +62,11 @@ class Localplay {
* This returns true / false if the player load * This returns true / false if the player load
* failed / worked * failed / worked
*/ */
public function player_loaded() { public function player_loaded()
{
if (is_object($this->_player)) { if (is_object($this->_player)) {
return true; return true;
} } else {
else {
return false; return false;
} }
@ -78,8 +77,8 @@ class Localplay {
* This makes the localplay/plugin information * This makes the localplay/plugin information
* human readable * human readable
*/ */
public function format() { public function format()
{
if (!is_object($this->_player)) { return false; } if (!is_object($this->_player)) { return false; }
$this->f_name = ucfirst($this->type); $this->f_name = ucfirst($this->type);
@ -95,8 +94,8 @@ class Localplay {
* Will interface with in order to make all this magical stuf work * Will interface with in order to make all this magical stuf work
* all LocalPlay modules should be located in /modules/<name>/<name>.class.php * all LocalPlay modules should be located in /modules/<name>/<name>.class.php
*/ */
private function _load_player() { private function _load_player()
{
if (!$this->type) { return false; } if (!$this->type) { return false; }
$filename = Config::get('prefix') . '/modules/localplay/' . $this->type . '.controller.php'; $filename = Config::get('prefix') . '/modules/localplay/' . $this->type . '.controller.php';
@ -125,8 +124,8 @@ class Localplay {
* is supported in the current player, if so it returns a 'skip to' * is supported in the current player, if so it returns a 'skip to'
* link, otherwise it returns just the text * link, otherwise it returns just the text
*/ */
public function format_name($name,$id) { public function format_name($name,$id)
{
$name = scrub_out($name); $name = scrub_out($name);
$name = Ajax::text('?page=localplay&action=command&command=skip&id=' . $id,$name,'localplay_skip_' . $id); $name = Ajax::text('?page=localplay&action=command&command=skip&id=' . $id,$name,'localplay_skip_' . $id);
return $name; return $name;
@ -137,8 +136,8 @@ class Localplay {
* get_controllers * get_controllers
* This returns the controllers that are currently loaded into this instance * This returns the controllers that are currently loaded into this instance
*/ */
public static function get_controllers() { public static function get_controllers()
{
/* First open the dir */ /* First open the dir */
$handle = opendir(Config::get('prefix') . '/modules/localplay'); $handle = opendir(Config::get('prefix') . '/modules/localplay');
@ -170,8 +169,8 @@ class Localplay {
* This returns true or false depending on if the specified controller * This returns true or false depending on if the specified controller
* is currently enabled * is currently enabled
*/ */
public static function is_enabled($controller) { public static function is_enabled($controller)
{
// Load the controller and then check for its preferences // Load the controller and then check for its preferences
$localplay = new Localplay($controller); $localplay = new Localplay($controller);
// If we can't even load it no sense in going on // If we can't even load it no sense in going on
@ -186,8 +185,8 @@ class Localplay {
* This runs the install for the localplay controller we've * This runs the install for the localplay controller we've
* currently got pimped out * currently got pimped out
*/ */
public function install() { public function install()
{
// Run the player's installer // Run the player's installer
$installed = $this->_player->install(); $installed = $this->_player->install();
@ -200,8 +199,8 @@ class Localplay {
* This runs the uninstall for the localplay controller we've * This runs the uninstall for the localplay controller we've
* currently pimped out * currently pimped out
*/ */
public function uninstall() { public function uninstall()
{
// Run the players uninstaller // Run the players uninstaller
$this->_player->uninstall(); $this->_player->uninstall();
@ -219,8 +218,8 @@ class Localplay {
* This function attempts to connect to the localplay * This function attempts to connect to the localplay
* player that we are using * player that we are using
*/ */
public function connect() { public function connect()
{
if (!$this->_player->connect()) { if (!$this->_player->connect()) {
debug_event('localplay','Error Unable to connect, check ' . $this->type . ' controller','1'); debug_event('localplay','Error Unable to connect, check ' . $this->type . ' controller','1');
return false; return false;
@ -235,8 +234,8 @@ class Localplay {
* This function passes NULL and calls the play function of the player * This function passes NULL and calls the play function of the player
* object * object
*/ */
public function play() { public function play()
{
if (!$this->_player->play()) { if (!$this->_player->play()) {
debug_event('localplay','Error Unable to start playback, check ' . $this->type . ' controller','1'); debug_event('localplay','Error Unable to start playback, check ' . $this->type . ' controller','1');
return false; return false;
@ -251,8 +250,8 @@ class Localplay {
* This functions passes NULl and calls the stop function of the player * This functions passes NULl and calls the stop function of the player
* object, it should recieve a true/false boolean value * object, it should recieve a true/false boolean value
*/ */
public function stop() { public function stop()
{
if (!$this->_player->stop()) { if (!$this->_player->stop()) {
debug_event('localplay','Error Unable to stop playback, check ' . $this->type . ' controller','1'); debug_event('localplay','Error Unable to stop playback, check ' . $this->type . ' controller','1');
return false; return false;
@ -265,8 +264,8 @@ class Localplay {
/** /**
* add * add
*/ */
public function add($object) { public function add($object)
{
debug_event('localplay', 'Deprecated add method called: ' . json_encode($object), 5); debug_event('localplay', 'Deprecated add method called: ' . json_encode($object), 5);
return false; return false;
@ -276,8 +275,8 @@ class Localplay {
* add_url * add_url
* This directly adds an URL to the localplay module. Is more betterer. * This directly adds an URL to the localplay module. Is more betterer.
*/ */
public function add_url(Stream_URL $url) { public function add_url(Stream_URL $url)
{
if (!$this->_player->add_url($url)) { if (!$this->_player->add_url($url)) {
debug_event('localplay', 'Unable to add url ' . $url . ', check ' . $this->type . ' controller', 1); debug_event('localplay', 'Unable to add url ' . $url . ', check ' . $this->type . ' controller', 1);
return false; return false;
@ -292,8 +291,8 @@ class Localplay {
* This turns the repeat feature of a localplay method on or * This turns the repeat feature of a localplay method on or
* off, takes a 0/1 value * off, takes a 0/1 value
*/ */
public function repeat($state) { public function repeat($state)
{
$data = $this->_player->repeat($state); $data = $this->_player->repeat($state);
if (!$data) { if (!$data) {
@ -309,8 +308,8 @@ class Localplay {
* This turns on the random feature of a localplay method * This turns on the random feature of a localplay method
* It takes a 0/1 value * It takes a 0/1 value
*/ */
public function random($state) { public function random($state)
{
$data = $this->_player->random($state); $data = $this->_player->random($state);
if (!$data) { if (!$data) {
@ -326,8 +325,8 @@ class Localplay {
* This returns current information about the state of the player * This returns current information about the state of the player
* There is an expected array format * There is an expected array format
*/ */
public function status() { public function status()
{
$data = $this->_player->status(); $data = $this->_player->status();
if (!count($data)) { if (!count($data)) {
@ -345,8 +344,8 @@ class Localplay {
* the array of current songs for display or whatever * the array of current songs for display or whatever
* an empty array is passed on failure * an empty array is passed on failure
*/ */
public function get() { public function get()
{
$data = $this->_player->get(); $data = $this->_player->get();
if (!count($data) OR !is_array($data)) { if (!count($data) OR !is_array($data)) {
@ -364,8 +363,8 @@ class Localplay {
* as passed in the variable it is a 0 - 100 scale the controller is * as passed in the variable it is a 0 - 100 scale the controller is
* responsible for adjusting the scale if nessecary * responsible for adjusting the scale if nessecary
*/ */
public function volume_set($value) { public function volume_set($value)
{
/* Make sure it's int and 0 - 100 */ /* Make sure it's int and 0 - 100 */
$value = int($value); $value = int($value);
@ -386,8 +385,8 @@ class Localplay {
* This function isn't required. It tells the daemon to increase the volume * This function isn't required. It tells the daemon to increase the volume
* by a pre-defined amount controlled by the controller * by a pre-defined amount controlled by the controller
*/ */
public function volume_up() { public function volume_up()
{
if (!$this->_player->volume_up()) { if (!$this->_player->volume_up()) {
debug_event('localplay','Error: Unable to increase volume, check ' . $this->type . ' controller','1'); debug_event('localplay','Error: Unable to increase volume, check ' . $this->type . ' controller','1');
return false; return false;
@ -402,8 +401,8 @@ class Localplay {
* This function isn't required. It tells the daemon to decrese the volume * This function isn't required. It tells the daemon to decrese the volume
* by a pre-defined amount controlled by the controller. * by a pre-defined amount controlled by the controller.
*/ */
public function volume_down() { public function volume_down()
{
if (!$this->_player->volume_down()) { if (!$this->_player->volume_down()) {
debug_event('localplay','Error: Unable to decrese volume, check ' . $this->type . ' controller','1'); debug_event('localplay','Error: Unable to decrese volume, check ' . $this->type . ' controller','1');
return false; return false;
@ -418,9 +417,9 @@ class Localplay {
* This function isn't required, It tells the daemon to mute all output * This function isn't required, It tells the daemon to mute all output
* It's up to the controller to decide what that actually entails * It's up to the controller to decide what that actually entails
*/ */
public function volume_mute() { public function volume_mute()
{
if (!$this->_player->volume(0)){ if (!$this->_player->volume(0)) {
debug_event('localplay','Error: Unable to mute volume, check ' . $this->type . ' controller','1'); debug_event('localplay','Error: Unable to mute volume, check ' . $this->type . ' controller','1');
return false; return false;
} }
@ -433,8 +432,8 @@ class Localplay {
* skip * skip
* This isn't a required function, it tells the daemon to skip to the specified song * This isn't a required function, it tells the daemon to skip to the specified song
*/ */
public function skip($track_id) { public function skip($track_id)
{
if (!$this->_player->skip($track_id)) { if (!$this->_player->skip($track_id)) {
debug_event('localplay','Error: Unable to skip to next song, check ' . $this->type . ' controller','1'); debug_event('localplay','Error: Unable to skip to next song, check ' . $this->type . ' controller','1');
return false; return false;
@ -449,8 +448,8 @@ class Localplay {
* This isn't a required function, it tells the daemon to go to the next * This isn't a required function, it tells the daemon to go to the next
* song * song
*/ */
public function next() { public function next()
{
if (!$this->_player->next()) { if (!$this->_player->next()) {
debug_event('localplay','Error: Unable to skip to next song, check ' . $this->type . ' controller','1'); debug_event('localplay','Error: Unable to skip to next song, check ' . $this->type . ' controller','1');
return false; return false;
@ -465,9 +464,8 @@ class Localplay {
* This isn't a required function, it tells the daemon to go the the previous * This isn't a required function, it tells the daemon to go the the previous
* song * song
*/ */
public function prev() { public function prev()
{
if (!$this->_player->prev()) { if (!$this->_player->prev()) {
debug_event('localplay','Error: Unable to skip to previous song, check ' . $this->type . ' controller','1'); debug_event('localplay','Error: Unable to skip to previous song, check ' . $this->type . ' controller','1');
return false; return false;
@ -482,8 +480,8 @@ class Localplay {
* This isn't a required function, it tells the daemon to pause the * This isn't a required function, it tells the daemon to pause the
* song * song
*/ */
public function pause() { public function pause()
{
if (!$this->_player->pause()) { if (!$this->_player->pause()) {
debug_event('localplay','Error: Unable to pause song, check ' . $this->type . ' controller','1'); debug_event('localplay','Error: Unable to pause song, check ' . $this->type . ' controller','1');
return false; return false;
@ -497,8 +495,8 @@ class Localplay {
* get_instances * get_instances
* This returns the instances of the current type * This returns the instances of the current type
*/ */
public function get_instances() { public function get_instances()
{
$instances = $this->_player->get_instances(); $instances = $this->_player->get_instances();
return $instances; return $instances;
@ -509,8 +507,8 @@ class Localplay {
* current_instance * current_instance
* This returns the UID of the current Instance * This returns the UID of the current Instance
*/ */
public function current_instance() { public function current_instance()
{
$data = $this->_player->get_instance(); $data = $this->_player->get_instance();
return $data['id']; return $data['id'];
@ -521,8 +519,8 @@ class Localplay {
* get_instance * get_instance
* This returns the specified instance * This returns the specified instance
*/ */
public function get_instance($uid) { public function get_instance($uid)
{
$data = $this->_player->get_instance($uid); $data = $this->_player->get_instance($uid);
return $data; return $data;
@ -533,8 +531,8 @@ class Localplay {
* update_instance * update_instance
* This updates the specified instance with a named array of data (_POST most likely) * This updates the specified instance with a named array of data (_POST most likely)
*/ */
public function update_instance($uid,$data) { public function update_instance($uid,$data)
{
$data = $this->_player->update_instance($uid,$data); $data = $this->_player->update_instance($uid,$data);
return $data; return $data;
@ -545,8 +543,8 @@ class Localplay {
* add_instance * add_instance
* This adds a new instance for the current controller type * This adds a new instance for the current controller type
*/ */
public function add_instance($data) { public function add_instance($data)
{
$this->_player->add_instance($data); $this->_player->add_instance($data);
} // add_instance } // add_instance
@ -555,8 +553,8 @@ class Localplay {
* delete_instance * delete_instance
* This removes an instance (it actually calls the players function) * This removes an instance (it actually calls the players function)
*/ */
public function delete_instance($instance_uid) { public function delete_instance($instance_uid)
{
$this->_player->delete_instance($instance_uid); $this->_player->delete_instance($instance_uid);
} // delete_instance } // delete_instance
@ -565,8 +563,8 @@ class Localplay {
* set_active_instance * set_active_instance
* This sets the active instance of the localplay controller * This sets the active instance of the localplay controller
*/ */
public function set_active_instance($instance) { public function set_active_instance($instance)
{
$this->_player->set_active_instance($instance); $this->_player->set_active_instance($instance);
} // set_active_instance } // set_active_instance
@ -576,8 +574,8 @@ class Localplay {
* This removes songs from the players playlist it takes a single ID as provided * This removes songs from the players playlist it takes a single ID as provided
* by the get command * by the get command
*/ */
public function delete_track($object_id) { public function delete_track($object_id)
{
if (!$this->_player->delete_track($object_id)) { if (!$this->_player->delete_track($object_id)) {
debug_event('localplay','Error: Unable to remove songs, check ' . $this->type . ' controller','1'); debug_event('localplay','Error: Unable to remove songs, check ' . $this->type . ' controller','1');
return false; return false;
@ -593,8 +591,8 @@ class Localplay {
* This removes every song from the players playlist as defined by the delete_all function * This removes every song from the players playlist as defined by the delete_all function
* map * map
*/ */
public function delete_all() { public function delete_all()
{
if (!$this->_player->clear_playlist()) { if (!$this->_player->clear_playlist()) {
debug_event('localplay','Error: Unable to delete entire playlist, check ' . $this->type . ' controller','1'); debug_event('localplay','Error: Unable to delete entire playlist, check ' . $this->type . ' controller','1');
return false; return false;
@ -609,8 +607,8 @@ class Localplay {
* This loads the fields from the localplay * This loads the fields from the localplay
* player and returns them * player and returns them
*/ */
public function get_instance_fields() { public function get_instance_fields()
{
$fields = $this->_player->instance_fields(); $fields = $this->_player->instance_fields();
return $fields; return $fields;
@ -622,8 +620,8 @@ class Localplay {
* This function returns a user friendly version * This function returns a user friendly version
* of the current player state * of the current player state
*/ */
public function get_user_state($state) { public function get_user_state($state)
{
switch ($state) { switch ($state) {
case 'play': case 'play':
return T_('Now Playing'); return T_('Now Playing');
@ -646,8 +644,8 @@ class Localplay {
* This attempts to return a nice user friendly * This attempts to return a nice user friendly
* currently playing string * currently playing string
*/ */
public function get_user_playing() { public function get_user_playing()
{
$status = $this->status(); $status = $this->status();
/* Format the track name */ /* Format the track name */
@ -666,4 +664,3 @@ class Localplay {
} // end localplay class } // end localplay class
?>

View file

@ -26,8 +26,8 @@
* This is the abstract class for any localplay controller * This is the abstract class for any localplay controller
* *
*/ */
abstract class localplay_controller { abstract class localplay_controller
{
// Required Functions // Required Functions
abstract public function add_url(Stream_URL $url); // Takes an array of song_ids abstract public function add_url(Stream_URL $url); // Takes an array of song_ids
abstract public function delete_track($object_id); // Takes a single object_id and removes it from the playlist abstract public function delete_track($object_id); // Takes a single object_id and removes it from the playlist
@ -55,8 +55,8 @@ abstract class localplay_controller {
* get_url * get_url
* This returns the URL for the passed object * This returns the URL for the passed object
*/ */
public function get_url($object) { public function get_url($object)
{
// This might not be an object! // This might not be an object!
if (!is_object($object)) { if (!is_object($object)) {
// Stupiidly we'll just blindly add it for now // Stupiidly we'll just blindly add it for now
@ -76,9 +76,8 @@ abstract class localplay_controller {
* This returns the Filename for the passed object, not * This returns the Filename for the passed object, not
* always possible * always possible
*/ */
public function get_file($object) { public function get_file($object)
{
} // get_file } // get_file
/** /**
@ -86,8 +85,8 @@ abstract class localplay_controller {
* This takes an Ampache URL and then returns the 'primary' part of it * This takes an Ampache URL and then returns the 'primary' part of it
* So that it's easier for localplay modules to return valid song information * So that it's easier for localplay modules to return valid song information
*/ */
public function parse_url($url) { public function parse_url($url)
{
// Define possible 'primary' keys // Define possible 'primary' keys
$primary_array = array('oid','demo_id','random'); $primary_array = array('oid','demo_id','random');
$data = array(); $data = array();

View file

@ -26,8 +26,8 @@
* This class handles the Mail * This class handles the Mail
* *
*/ */
class Mailer { class Mailer
{
// The message, recipient and from // The message, recipient and from
public $message; public $message;
public $subject; public $subject;
@ -41,8 +41,8 @@ class Mailer {
* *
* This does nothing. Much like goggles. * This does nothing. Much like goggles.
*/ */
public function __construct() { public function __construct()
{
// Eh bien. // Eh bien.
} // Constructor } // Constructor
@ -52,7 +52,8 @@ class Mailer {
* *
* Checks whether what we have looks like a valid address. * Checks whether what we have looks like a valid address.
*/ */
public static function validate_address($address) { public static function validate_address($address)
{
return PHPMailer::ValidateAddress($address); return PHPMailer::ValidateAddress($address);
} }
@ -62,7 +63,8 @@ class Mailer {
* Does the config magic to figure out the "system" email sender and * Does the config magic to figure out the "system" email sender and
* sets it as the sender. * sets it as the sender.
*/ */
public function set_default_sender() { public function set_default_sender()
{
$user = Config::get('mail_user'); $user = Config::get('mail_user');
if (!$user) { if (!$user) {
$user = 'info'; $user = 'info';
@ -72,7 +74,7 @@ class Mailer {
if (!$domain) { if (!$domain) {
$domain = 'example.com'; $domain = 'example.com';
} }
$fromname = Config::get('mail_name'); $fromname = Config::get('mail_name');
if (!$fromname) { if (!$fromname) {
$fromname = 'Ampache'; $fromname = 'Ampache';
@ -87,8 +89,8 @@ class Mailer {
* This returns an array of userids for people who have e-mail * This returns an array of userids for people who have e-mail
* addresses based on the passed filter * addresses 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':
@ -123,30 +125,27 @@ class Mailer {
* This should be run if we want to add some statistics to this e-mail, * This should be run if we want to add some statistics to this e-mail,
* appends to self::$message * appends to self::$message
*/ */
public function add_statistics($methods) { public function add_statistics($methods)
{
} // add_statistics } // add_statistics
/** /**
* send * send
* This actually sends the mail, how amazing * This actually sends the mail, how amazing
*/ */
public function send($phpmailer = null) { public function send($phpmailer = null)
{
$mailtype = Config::get('mail_type'); $mailtype = Config::get('mail_type');
if ($phpmailer == null) { if ($phpmailer == null) {
$mail = new PHPMailer(); $mail = new PHPMailer();
$recipient_name = $this->recipient_name; $recipient_name = $this->recipient_name;
if(function_exists('mb_encode_mimeheader')) { if (function_exists('mb_encode_mimeheader')) {
$recipient_name = mb_encode_mimeheader($recipient_name); $recipient_name = mb_encode_mimeheader($recipient_name);
} }
$mail->AddAddress($this->recipient, $recipient_name); $mail->AddAddress($this->recipient, $recipient_name);
} } else {
else {
$mail = $phpmailer; $mail = $phpmailer;
} }
@ -157,7 +156,7 @@ class Mailer {
$mail->FromName = $this->sender_name; $mail->FromName = $this->sender_name;
$mail->Subject = $this->subject; $mail->Subject = $this->subject;
if(function_exists('mb_eregi_replace')) { if (function_exists('mb_eregi_replace')) {
$this->message = mb_eregi_replace("\r\n", "\n", $this->message); $this->message = mb_eregi_replace("\r\n", "\n", $this->message);
} }
$mail->Body = $this->message; $mail->Body = $this->message;
@ -174,12 +173,12 @@ class Mailer {
$mailpass = Config::get('mail_auth_pass'); $mailpass = Config::get('mail_auth_pass');
$mailpass = $mailpass ? $mailpass : ''; $mailpass = $mailpass ? $mailpass : '';
switch($mailtype) { switch ($mailtype) {
case 'smtp': case 'smtp':
$mail->IsSMTP(); $mail->IsSMTP();
$mail->Host = $mailhost; $mail->Host = $mailhost;
$mail->Port = $mailport; $mail->Port = $mailport;
if($mailauth == true) { if ($mailauth == true) {
$mail->SMTPAuth = true; $mail->SMTPAuth = true;
$mail->Username = $mailuser; $mail->Username = $mailuser;
$mail->Password = $mailpass; $mail->Password = $mailpass;
@ -199,18 +198,19 @@ class Mailer {
} }
$retval = $mail->send(); $retval = $mail->send();
if( $retval == true ) { if ($retval == true) {
return true; return true;
} else { } else {
return false; return false;
} }
} // send } // send
public function send_to_group($group_name) { public function send_to_group($group_name)
{
$mail = new PHPMailer(); $mail = new PHPMailer();
foreach(self::get_users($group_name) as $member) { foreach (self::get_users($group_name) as $member) {
if(function_exists('mb_encode_mimeheader')) { if (function_exists('mb_encode_mimeheader')) {
$member['fullname'] = mb_encode_mimeheader($member['fullname']); $member['fullname'] = mb_encode_mimeheader($member['fullname']);
} }
$mail->AddBCC($member['email'], $member['fullname']); $mail->AddBCC($member['email'], $member['fullname']);
@ -220,4 +220,3 @@ class Mailer {
} }
} // Mailer class } // Mailer class
?>

View file

@ -26,12 +26,12 @@
* work, this lists all required functions and the expected * work, this lists all required functions and the expected
* input * input
*/ */
interface media { interface media
{
/** /**
* format * format
* *
* Creates the gussied-up member variables for output * Creates the gussied-up member variables for output
*/ */
public function format(); public function format();
@ -47,7 +47,7 @@ interface media {
* play_url * play_url
* *
* Returns the url to stream the specified object * Returns the url to stream the specified object
* *
*/ */
public static function play_url($oid); public static function play_url($oid);
@ -68,4 +68,3 @@ interface media {
public function has_flag(); public function has_flag();
} // end interface } // end interface
?>

View file

@ -23,13 +23,13 @@
// A magical class filled with ponies // A magical class filled with ponies
class memory_object { class memory_object
{
private $_data = array(); private $_data = array();
public $properties; public $properties;
public function __construct($data) { public function __construct($data)
{
foreach ($data as $key => $value) { foreach ($data as $key => $value) {
if (in_array($key, $this->properties)) { if (in_array($key, $this->properties)) {
$this->_data[$key] = $value; $this->_data[$key] = $value;
@ -38,14 +38,16 @@ class memory_object {
} }
public function __set($name, $value) { public function __set($name, $value)
{
if (!in_array($name, $this->properties)) { if (!in_array($name, $this->properties)) {
return false; return false;
} }
$this->_data[$name] = $value; $this->_data[$name] = $value;
} }
public function __get($name) { public function __get($name)
{
if (!in_array($name, $this->properties)) { if (!in_array($name, $this->properties)) {
return false; return false;
} }

View file

@ -27,8 +27,8 @@
* This class handles playlists in ampache. it references the playlist* tables * This class handles playlists in ampache. it references the playlist* tables
* *
*/ */
class Playlist extends playlist_object { class Playlist extends playlist_object
{
/* Variables from the database */ /* Variables from the database */
public $genre; public $genre;
public $date; public $date;
@ -41,8 +41,8 @@ class Playlist extends playlist_object {
* This takes a playlist_id as an optional argument and gathers the information * This takes a playlist_id as an optional argument and gathers the information
* if not playlist_id is passed returns false (or if it isn't found * if not playlist_id is passed returns false (or if it isn't found
*/ */
public function __construct($id) { public function __construct($id)
{
$info = $this->get_info($id); $info = $this->get_info($id);
foreach ($info as $key=>$value) { foreach ($info as $key=>$value) {
@ -56,16 +56,17 @@ class Playlist extends playlist_object {
* *
* Clean dead items out of playlists * Clean dead items out of playlists
*/ */
public static function gc() { public static function gc()
Dba::write("DELETE FROM `playlist_data` USING `playlist_data` LEFT JOIN `song` ON `song`.`id` = `playlist_data`.`object_id` WHERE `song`.`file` IS NULL AND `playlist_data`.`object_type`='song'"); {
Dba::write("DELETE FROM `playlist_data` USING `playlist_data` LEFT JOIN `song` ON `song`.`id` = `playlist_data`.`object_id` WHERE `song`.`file` IS NULL AND `playlist_data`.`object_type`='song'");
} }
/** /**
* build_cache * build_cache
* This is what builds the cache from the objects * This is what builds the cache from the objects
*/ */
public static function build_cache($ids) { public static function build_cache($ids)
{
if (!count($ids)) { return false; } if (!count($ids)) { return false; }
$idlist = '(' . implode(',',$ids) . ')'; $idlist = '(' . implode(',',$ids) . ')';
@ -83,7 +84,8 @@ class Playlist extends playlist_object {
* get_playlists * get_playlists
* Returns a list of playlists accessible by the current user. * Returns a list of playlists accessible by the current user.
*/ */
public static function get_playlists() { public static function get_playlists()
{
$sql = "SELECT `id` from `playlist` WHERE `type`='public' OR " . $sql = "SELECT `id` from `playlist` WHERE `type`='public' OR " .
"`user`='" . $GLOBALS['user']->id . "' ORDER BY `name`"; "`user`='" . $GLOBALS['user']->id . "' ORDER BY `name`";
$db_results = Dba::read($sql); $db_results = Dba::read($sql);
@ -102,7 +104,8 @@ class Playlist extends playlist_object {
* This takes the current playlist object and gussies it up a little * This takes the current playlist object and gussies it up a little
* bit so it is presentable to the users * bit so it is presentable to the users
*/ */
public function format() { public function format()
{
parent::format(); parent::format();
$this->f_link = '<a href="' . Config::get('web_path') . '/playlist.php?action=show_playlist&amp;playlist_id=' . $this->id . '">' . $this->f_name . '</a>'; $this->f_link = '<a href="' . Config::get('web_path') . '/playlist.php?action=show_playlist&amp;playlist_id=' . $this->id . '">' . $this->f_name . '</a>';
@ -113,8 +116,8 @@ class Playlist extends playlist_object {
* Returns the single item on the playlist and all of it's information, restrict * Returns the single item on the playlist and all of it's information, restrict
* it to this Playlist * it to this Playlist
*/ */
public function get_track($track_id) { public function get_track($track_id)
{
$sql = "SELECT * FROM `playlist_data` WHERE `id` = ? AND `playlist` = ?"; $sql = "SELECT * FROM `playlist_data` WHERE `id` = ? AND `playlist` = ?";
$db_results = Dba::read($sql, array($track_id, $playlist_id)); $db_results = Dba::read($sql, array($track_id, $playlist_id));
@ -126,12 +129,12 @@ class Playlist extends playlist_object {
/** /**
* get_items * get_items
* This returns an array of playlist songs that are in this playlist. * This returns an array of playlist songs that are in this playlist.
* Because the same song can be on the same playlist twice they are * Because the same song can be on the same playlist twice they are
* keyed by the uid from playlist_data * keyed by the uid from playlist_data
*/ */
public function get_items() { public function get_items()
{
$results = array(); $results = array();
$sql = "SELECT `id`,`object_id`,`object_type`,`track` FROM `playlist_data` WHERE `playlist`= ? ORDER BY `track`"; $sql = "SELECT `id`,`object_id`,`object_type`,`track` FROM `playlist_data` WHERE `playlist`= ? ORDER BY `track`";
@ -154,8 +157,8 @@ class Playlist extends playlist_object {
* get_random_items * get_random_items
* This is the same as before but we randomize the buggers! * This is the same as before but we randomize the buggers!
*/ */
public function get_random_items($limit='') { public function get_random_items($limit='')
{
$results = array(); $results = array();
$limit_sql = $limit ? 'LIMIT ' . intval($limit) : ''; $limit_sql = $limit ? 'LIMIT ' . intval($limit) : '';
@ -181,8 +184,8 @@ class Playlist extends playlist_object {
* This is called by the batch script, because we can't pass in Dynamic objects they pulled once and then their * This is called by the batch script, because we can't pass in Dynamic objects they pulled once and then their
* target song.id is pushed into the array * target song.id is pushed into the array
*/ */
function get_songs() { public function get_songs()
{
$results = array(); $results = array();
$sql = "SELECT * FROM `playlist_data` WHERE `playlist` = ? ORDER BY `track`"; $sql = "SELECT * FROM `playlist_data` WHERE `playlist` = ? ORDER BY `track`";
@ -192,8 +195,7 @@ class Playlist extends playlist_object {
if ($r['dyn_song']) { if ($r['dyn_song']) {
$array = $this->get_dyn_songs($r['dyn_song']); $array = $this->get_dyn_songs($r['dyn_song']);
$results = array_merge($array,$results); $results = array_merge($array,$results);
} } else {
else {
$results[] = $r['object_id']; $results[] = $r['object_id'];
} }
@ -208,8 +210,8 @@ class Playlist extends playlist_object {
* This simply returns a int of how many song elements exist in this playlist * This simply returns a int of how many song elements exist in this playlist
* For now let's consider a dyn_song a single entry * For now let's consider a dyn_song a single entry
*/ */
public function get_song_count() { public function get_song_count()
{
$sql = "SELECT COUNT(`id`) FROM `playlist_data` WHERE `playlist` = ?"; $sql = "SELECT COUNT(`id`) FROM `playlist_data` WHERE `playlist` = ?";
$db_results = Dba::read($sql, array($this->id)); $db_results = Dba::read($sql, array($this->id));
@ -218,13 +220,13 @@ class Playlist extends playlist_object {
return $results['0']; return $results['0'];
} // get_song_count } // get_song_count
/** /**
* get_total_duration * get_total_duration
* Get the total duration of all songs. * Get the total duration of all songs.
*/ */
public function get_total_duration() { public function get_total_duration()
{
$songs = self::get_songs(); $songs = self::get_songs();
$idlist = '(' . implode(',', $songs) . ')'; $idlist = '(' . implode(',', $songs) . ')';
@ -242,8 +244,8 @@ class Playlist extends playlist_object {
* This returns the specified users playlists as an array of * This returns the specified users playlists as an array of
* playlist ids * playlist ids
*/ */
public static function get_users($user_id) { public static function get_users($user_id)
{
$results = array(); $results = array();
$sql = "SELECT `id` FROM `playlist` WHERE `user` = ? ORDER BY `name`"; $sql = "SELECT `id` FROM `playlist` WHERE `user` = ? ORDER BY `name`";
@ -261,8 +263,8 @@ class Playlist extends playlist_object {
* update * update
* This function takes a key'd array of data and runs updates * This function takes a key'd array of data and runs updates
*/ */
public function update($data) { public function update($data)
{
if ($data['name'] != $this->name) { if ($data['name'] != $this->name) {
$this->update_name($data['name']); $this->update_name($data['name']);
} }
@ -276,8 +278,8 @@ class Playlist extends playlist_object {
* update_type * update_type
* This updates the playlist type, it calls the generic update_item function * This updates the playlist type, it calls the generic update_item function
*/ */
private function update_type($new_type) { private function update_type($new_type)
{
if ($this->_update_item('type',$new_type,'50')) { if ($this->_update_item('type',$new_type,'50')) {
$this->type = $new_type; $this->type = $new_type;
} }
@ -288,8 +290,8 @@ class Playlist extends playlist_object {
* update_name * update_name
* This updates the playlist name, it calls the generic update_item function * This updates the playlist name, it calls the generic update_item function
*/ */
private function update_name($new_name) { private function update_name($new_name)
{
if ($this->_update_item('name',$new_name,'50')) { if ($this->_update_item('name',$new_name,'50')) {
$this->name = $new_name; $this->name = $new_name;
} }
@ -300,8 +302,8 @@ class Playlist extends playlist_object {
* _update_item * _update_item
* This is the generic update function, it does the escaping and error checking * This is the generic update function, it does the escaping and error checking
*/ */
private function _update_item($field,$value,$level) { private function _update_item($field,$value,$level)
{
if ($GLOBALS['user']->id != $this->user AND !Access::check('interface',$level)) { if ($GLOBALS['user']->id != $this->user AND !Access::check('interface',$level)) {
return false; return false;
} }
@ -317,8 +319,8 @@ class Playlist extends playlist_object {
* update_track_number * update_track_number
* This takes a playlist_data.id and a track (int) and updates the track value * This takes a playlist_data.id and a track (int) and updates the track value
*/ */
public function update_track_number($track_id,$track) { public function update_track_number($track_id,$track)
{
$sql = "UPDATE `playlist_data` SET `track` = ? WHERE `id` = ? AND `playlist` = ?"; $sql = "UPDATE `playlist_data` SET `track` = ? WHERE `id` = ? AND `playlist` = ?";
$db_results = Dba::write($sql, array($track, $track_id, $this->id)); $db_results = Dba::write($sql, array($track, $track_id, $this->id));
@ -330,8 +332,8 @@ class Playlist extends playlist_object {
* if you want to add a dyn_song you need to use the one shot function * if you want to add a dyn_song you need to use the one shot function
* add_dyn_song * add_dyn_song
*/ */
public function add_songs($song_ids=array(),$ordered=false) { public function add_songs($song_ids=array(),$ordered=false)
{
/* We need to pull the current 'end' track and then use that to /* We need to pull the current 'end' track and then use that to
* append, rather then integrate take end track # and add it to * append, rather then integrate take end track # and add it to
* $song->track add one to make sure it really is 'next' * $song->track add one to make sure it really is 'next'
@ -349,8 +351,7 @@ class Playlist extends playlist_object {
// Based on the ordered prop we use track + base or just $i++ // Based on the ordered prop we use track + base or just $i++
if (!$ordered) { if (!$ordered) {
$track = $song->track + $base_track; $track = $song->track + $base_track;
} } else {
else {
$i++; $i++;
$track = $base_track + $i; $track = $base_track + $i;
} }
@ -371,8 +372,8 @@ class Playlist extends playlist_object {
* This function creates an empty playlist, gives it a name and type * This function creates an empty playlist, gives it a name and type
* Assumes $GLOBALS['user']->id as the user * Assumes $GLOBALS['user']->id as the user
*/ */
public static function create($name,$type) { public static function create($name,$type)
{
$sql = "INSERT INTO `playlist` (`name`,`user`,`type`,`date`) VALUES (?, ?, ?, ?)"; $sql = "INSERT INTO `playlist` (`name`,`user`,`type`,`date`) VALUES (?, ?, ?, ?)";
$db_results = Dba::write($sql, array($name, $GLOBALS['user']->id, $type, time())); $db_results = Dba::write($sql, array($name, $GLOBALS['user']->id, $type, time()));
@ -386,8 +387,8 @@ class Playlist extends playlist_object {
* set_items * set_items
* This calls the get_items function and sets it to $this->items which is an array in this object * This calls the get_items function and sets it to $this->items which is an array in this object
*/ */
function set_items() { public function set_items()
{
$this->items = $this->get_items(); $this->items = $this->get_items();
} // set_items } // set_items
@ -398,8 +399,8 @@ class Playlist extends playlist_object {
* and numbers them in a liner fashion, not allowing for * and numbers them in a liner fashion, not allowing for
* the same track # twice, this is an optional function * the same track # twice, this is an optional function
*/ */
public function normalize_tracks() { public function normalize_tracks()
{
/* First get all of the songs in order of their tracks */ /* First get all of the songs in order of their tracks */
$sql = "SELECT `id` FROM `playlist_data` WHERE `playlist` = ? ORDER BY `track` ASC"; $sql = "SELECT `id` FROM `playlist_data` WHERE `playlist` = ? ORDER BY `track` ASC";
$db_results = Dba::read($sql, array($this->id)); $db_results = Dba::read($sql, array($this->id));
@ -415,7 +416,7 @@ class Playlist extends playlist_object {
$i++; $i++;
} // end while results } // end while results
foreach($results as $data) { foreach ($results as $data) {
$sql = "UPDATE `playlist_data` SET `track` = ? WHERE `id` = ?"; $sql = "UPDATE `playlist_data` SET `track` = ? WHERE `id` = ?";
$db_results = Dba::write($sql, array($data['track'], $data['id'])); $db_results = Dba::write($sql, array($data['track'], $data['id']));
} // foreach re-ordered results } // foreach re-ordered results
@ -428,21 +429,21 @@ class Playlist extends playlist_object {
* delete_track * delete_track
* this deletes a single track, you specify the playlist_data.id here * this deletes a single track, you specify the playlist_data.id here
*/ */
public function delete_track($id) { public function delete_track($id)
{
$sql = "DELETE FROM `playlist_data` WHERE `playlist_data`.`playlist` = ? AND `playlist_data`.`id` = ? LIMIT 1"; $sql = "DELETE FROM `playlist_data` WHERE `playlist_data`.`playlist` = ? AND `playlist_data`.`id` = ? LIMIT 1";
$db_results = Dba::write($sql, array($this->id, $id)); $db_results = Dba::write($sql, array($this->id, $id));
return true; return true;
} // delete_track } // delete_track
/** /**
* delete_track_number * delete_track_number
* this deletes a single track by it's track #, you specify the playlist_data.track here * this deletes a single track by it's track #, you specify the playlist_data.track here
*/ */
public function delete_track_number($track) { public function delete_track_number($track)
{
$sql = "DELETE FROM `playlist_data` WHERE `playlist_data`.`playlist` = ? AND `playlist_data`.`track` = ? LIMIT 1"; $sql = "DELETE FROM `playlist_data` WHERE `playlist_data`.`playlist` = ? AND `playlist_data`.`track` = ? LIMIT 1";
$db_results = Dba::write($sql, array($this->id, $track)); $db_results = Dba::write($sql, array($this->id, $track));
@ -454,8 +455,8 @@ class Playlist extends playlist_object {
* delete * delete
* This deletes the current playlist and all associated data * This deletes the current playlist and all associated data
*/ */
public function delete() { public function delete()
{
$sql = "DELETE FROM `playlist_data` WHERE `playlist` = ?"; $sql = "DELETE FROM `playlist_data` WHERE `playlist` = ?";
$db_results = Dba::write($sql, array($this->id)); $db_results = Dba::write($sql, array($this->id));

View file

@ -11,7 +11,7 @@
* *
* 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
@ -24,8 +24,8 @@
* playlist_object * playlist_object
* Abstracting out functionality needed by both normal and smart playlists * Abstracting out functionality needed by both normal and smart playlists
*/ */
abstract class playlist_object extends database_object { abstract class playlist_object extends database_object
{
// Database variables // Database variables
public $id; public $id;
public $name; public $name;
@ -37,8 +37,8 @@ abstract class playlist_object extends database_object {
* This takes the current playlist object and gussies it up a little * This takes the current playlist object and gussies it up a little
* bit so it is presentable to the users * bit so it is presentable to the users
*/ */
public function format() { public function format()
{
$this->f_name = UI::truncate($this->name,Config::get('ellipse_threshold_title')); $this->f_name = UI::truncate($this->name,Config::get('ellipse_threshold_title'));
$this->f_type = ($this->type == 'private') ? UI::get_icon('lock', T_('Private')) : ''; $this->f_type = ($this->type == 'private') ? UI::get_icon('lock', T_('Private')) : '';
@ -53,15 +53,14 @@ abstract class playlist_object extends database_object {
* This function returns true or false if the current user * This function returns true or false if the current user
* has access to this playlist * has access to this playlist
*/ */
public function has_access() { public function has_access()
{
if (!Access::check('interface','25')) { if (!Access::check('interface','25')) {
return false; return false;
} }
if ($this->user == $GLOBALS['user']->id) { if ($this->user == $GLOBALS['user']->id) {
return true; return true;
} } else {
else {
return Access::check('interface','100'); return Access::check('interface','100');
} }

View file

@ -20,8 +20,8 @@
* *
*/ */
class Plugin { class Plugin
{
/* Base Variables */ /* Base Variables */
public $name; public $name;
@ -33,8 +33,8 @@ class Plugin {
* This constructor loads the Plugin config file which defines how to * This constructor loads the Plugin config file which defines how to
* install/uninstall the plugin from Ampache's database * install/uninstall the plugin from Ampache's database
*/ */
public function __construct($name) { public function __construct($name)
{
/* Load the plugin */ /* Load the plugin */
if (!$this->_get_info($name)) { if (!$this->_get_info($name)) {
return false; return false;
@ -50,8 +50,8 @@ class Plugin {
* This actually loads the config file for the plugin the name of the * This actually loads the config file for the plugin the name of the
* class contained within the config file must be Plugin[NAME OF FILE] * class contained within the config file must be Plugin[NAME OF FILE]
*/ */
public function _get_info($name) { public function _get_info($name)
{
/* Require the file we want */ /* Require the file we want */
require_once Config::get('prefix') . '/modules/plugins/' . $name . '.plugin.php'; require_once Config::get('prefix') . '/modules/plugins/' . $name . '.plugin.php';
@ -71,8 +71,8 @@ class Plugin {
* get_plugins * get_plugins
* This returns an array of plugin names * This returns an array of plugin names
*/ */
public static function get_plugins($type='') { public static function get_plugins($type='')
{
$results = array(); $results = array();
// Open up the plugin dir // Open up the plugin dir
@ -118,12 +118,12 @@ class Plugin {
* is_valid * is_valid
* This checks to make sure the plugin has the required functions and * This checks to make sure the plugin has the required functions and
* settings. Ampache requires public variables name, description, and * settings. Ampache requires public variables name, description, and
* version (as an int), and methods install, uninstall, and load. We * version (as an int), and methods install, uninstall, and load. We
* also check that Ampache's database version falls within the min/max * also check that Ampache's database version falls within the min/max
* version specified by the plugin. * version specified by the plugin.
*/ */
function is_valid() { public function is_valid()
{
/* Check the plugin to make sure it's got the needed vars */ /* Check the plugin to make sure it's got the needed vars */
if (!strlen($this->_plugin->name)) { if (!strlen($this->_plugin->name)) {
return false; return false;
@ -169,8 +169,8 @@ class Plugin {
* This checks to see if the specified plugin is currently installed in * This checks to see if the specified plugin is currently installed in
* the database, it doesn't check the files for integrity * the database, it doesn't check the files for integrity
*/ */
public static function is_installed($plugin_name) { public static function is_installed($plugin_name)
{
/* All we do is check the version */ /* All we do is check the version */
return self::get_plugin_version($plugin_name); return self::get_plugin_version($plugin_name);
@ -178,11 +178,12 @@ class Plugin {
/** /**
* install * install
* This runs the install function of the plugin and inserts a row into * This runs the install function of the plugin and inserts a row into
* the update_info table to indicate that it's installed. * the update_info table to indicate that it's installed.
*/ */
public function install() { public function install()
if ($this->_plugin->install() && {
if ($this->_plugin->install() &&
$this->set_plugin_version($this->_plugin->version)) { $this->set_plugin_version($this->_plugin->version)) {
return true; return true;
} }
@ -192,11 +193,11 @@ class Plugin {
/** /**
* uninstall * uninstall
* This runs the uninstall function of the plugin and removes the row * This runs the uninstall function of the plugin and removes the row
* from the update_info table to indicate that it isn't installed. * from the update_info table to indicate that it isn't installed.
*/ */
public function uninstall() { public function uninstall()
{
$this->_plugin->uninstall(); $this->_plugin->uninstall();
$this->remove_plugin_version(); $this->remove_plugin_version();
@ -205,12 +206,13 @@ class Plugin {
/** /**
* upgrade * upgrade
* This runs the upgrade function of the plugin (if it exists) and * This runs the upgrade function of the plugin (if it exists) and
* updates the database to indicate our new version. * updates the database to indicate our new version.
*/ */
public function upgrade() { public function upgrade()
{
if (method_exists($this->_plugin, 'upgrade')) { if (method_exists($this->_plugin, 'upgrade')) {
if($this->_plugin->upgrade()) { if ($this->_plugin->upgrade()) {
$this->set_plugin_version($this->_plugin->version); $this->set_plugin_version($this->_plugin->version);
} }
} }
@ -220,7 +222,8 @@ class Plugin {
* load * load
* This calls the plugin's load function * This calls the plugin's load function
*/ */
public function load() { public function load()
{
$GLOBALS['user']->set_preferences(); $GLOBALS['user']->set_preferences();
return $this->_plugin->load(); return $this->_plugin->load();
} }
@ -229,8 +232,8 @@ class Plugin {
* get_plugin_version * get_plugin_version
* This returns the version of the specified plugin * This returns the version of the specified plugin
*/ */
public static function get_plugin_version($plugin_name) { public static function get_plugin_version($plugin_name)
{
$name = Dba::escape('Plugin_' . $plugin_name); $name = Dba::escape('Plugin_' . $plugin_name);
$sql = "SELECT * FROM `update_info` WHERE `key`='$name'"; $sql = "SELECT * FROM `update_info` WHERE `key`='$name'";
@ -248,8 +251,8 @@ class Plugin {
* get_ampache_db_version * get_ampache_db_version
* This function returns the Ampache database version * This function returns the Ampache database version
*/ */
function get_ampache_db_version() { public function get_ampache_db_version()
{
$sql = "SELECT * FROM `update_info` WHERE `key`='db_version'"; $sql = "SELECT * FROM `update_info` WHERE `key`='db_version'";
$db_results = Dba::read($sql); $db_results = Dba::read($sql);
@ -263,8 +266,8 @@ class Plugin {
* set_plugin_version * set_plugin_version
* This sets the plugin version in the update_info table * This sets the plugin version in the update_info table
*/ */
public function set_plugin_version($version) { public function set_plugin_version($version)
{
$name = Dba::escape('Plugin_' . $this->_plugin->name); $name = Dba::escape('Plugin_' . $this->_plugin->name);
$version = Dba::escape($version); $version = Dba::escape($version);
@ -279,8 +282,8 @@ class Plugin {
* remove_plugin_version * remove_plugin_version
* This removes the version row from the db done on uninstall * This removes the version row from the db done on uninstall
*/ */
public function remove_plugin_version() { public function remove_plugin_version()
{
$name = Dba::escape('Plugin_' . $this->_plugin->name); $name = Dba::escape('Plugin_' . $this->_plugin->name);
$sql = "DELETE FROM `update_info` WHERE `key`='$name'"; $sql = "DELETE FROM `update_info` WHERE `key`='$name'";
@ -291,4 +294,3 @@ class Plugin {
} // remove_plugin_version } // remove_plugin_version
} //end plugin class } //end plugin class
?>

View file

@ -27,14 +27,14 @@
* This handles all of the preference stuff for Ampache * This handles all of the preference stuff for Ampache
* *
*/ */
class Preference { class Preference
{
/** /**
* __constructor * __constructor
* This does nothing... amazing isn't it! * This does nothing... amazing isn't it!
*/ */
private function __construct() { private function __construct()
{
// Rien a faire // Rien a faire
} // __construct } // __construct
@ -43,21 +43,19 @@ class Preference {
* update * update
* This updates a single preference from the given name or id * This updates a single preference from the given name or id
*/ */
public static function update($preference,$user_id,$value,$applytoall='') { public static function update($preference,$user_id,$value,$applytoall='')
{
// First prepare // First prepare
if (!is_numeric($preference)) { if (!is_numeric($preference)) {
$id = self::id_from_name($preference); $id = self::id_from_name($preference);
$name = $preference; $name = $preference;
} } else {
else {
$name = self::name_from_id($preference); $name = self::name_from_id($preference);
$id = $preference; $id = $preference;
} }
if ($applytoall AND Access::check('interface','100')) { if ($applytoall AND Access::check('interface','100')) {
$user_check = ""; $user_check = "";
} } else {
else {
$user_check = " AND `user`='$user_id'"; $user_check = " AND `user`='$user_id'";
} }
@ -70,8 +68,7 @@ class Preference {
$db_results = Dba::write($sql); $db_results = Dba::write($sql);
Preference::clear_from_session(); Preference::clear_from_session();
return true; return true;
} } else {
else {
debug_event('denied',$GLOBALS['user']->username . ' attempted to update ' . $name . ' but does not have sufficient permissions','3'); debug_event('denied',$GLOBALS['user']->username . ' attempted to update ' . $name . ' but does not have sufficient permissions','3');
} }
@ -82,13 +79,12 @@ class Preference {
* update_level * update_level
* This takes a preference ID and updates the level required to update it (performed by an admin) * This takes a preference ID and updates the level required to update it (performed by an admin)
*/ */
public static function update_level($preference,$level) { public static function update_level($preference,$level)
{
// First prepare // First prepare
if (!is_numeric($preference)) { if (!is_numeric($preference)) {
$preference_id = self::id_from_name($preference); $preference_id = self::id_from_name($preference);
} } else {
else {
$preference_id = $preference; $preference_id = $preference;
} }
@ -106,8 +102,8 @@ class Preference {
* update_all * update_all
* This takes a preference id and a value and updates all users with the new info * This takes a preference id and a value and updates all users with the new info
*/ */
public static function update_all($preference_id,$value) { public static function update_all($preference_id,$value)
{
$preference_id = Dba::escape($preference_id); $preference_id = Dba::escape($preference_id);
$value = Dba::escape($value); $value = Dba::escape($value);
@ -122,8 +118,8 @@ class Preference {
* exists * exists
* This just checks to see if a preference currently exists * This just checks to see if a preference currently exists
*/ */
public static function exists($preference) { public static function exists($preference)
{
// We assume it's the name // We assume it's the name
$name = Dba::escape($preference); $name = Dba::escape($preference);
$sql = "SELECT * FROM `preference` WHERE `name`='$name'"; $sql = "SELECT * FROM `preference` WHERE `name`='$name'";
@ -138,8 +134,8 @@ class Preference {
* This checks to see if the current user has access to modify this preference * This checks to see if the current user has access to modify this preference
* as defined by the preference name * as defined by the preference name
*/ */
public static function has_access($preference) { public static function has_access($preference)
{
// Nothing for those demo thugs // Nothing for those demo thugs
if (Config::get('demo_mode')) { return false; } if (Config::get('demo_mode')) { return false; }
@ -161,8 +157,8 @@ class Preference {
* id_from_name * id_from_name
* This takes a name and returns the id * This takes a name and returns the id
*/ */
public static function id_from_name($name) { public static function id_from_name($name)
{
$name = Dba::escape($name); $name = Dba::escape($name);
$sql = "SELECT `id` FROM `preference` WHERE `name`='$name'"; $sql = "SELECT `id` FROM `preference` WHERE `name`='$name'";
@ -179,8 +175,8 @@ class Preference {
* This returns the name from an id, it's the exact opposite * This returns the name from an id, it's the exact opposite
* of the function above it, amazing! * of the function above it, amazing!
*/ */
public static function name_from_id($id) { public static function name_from_id($id)
{
$id = Dba::escape($id); $id = Dba::escape($id);
$sql = "SELECT `name` FROM `preference` WHERE `id`='$id'"; $sql = "SELECT `name` FROM `preference` WHERE `id`='$id'";
@ -197,8 +193,8 @@ class Preference {
* This returns an array of the names of the different possible sections * This returns an array of the names of the different possible sections
* it ignores the 'internal' catagory * it ignores the 'internal' catagory
*/ */
public static function get_catagories() { public static function get_catagories()
{
$sql = "SELECT `preference`.`catagory` FROM `preference` GROUP BY `catagory` ORDER BY `catagory`"; $sql = "SELECT `preference`.`catagory` FROM `preference` GROUP BY `catagory` ORDER BY `catagory`";
$db_results = Dba::read($sql); $db_results = Dba::read($sql);
@ -218,8 +214,8 @@ class Preference {
* get_all * get_all
* This returns a nice flat array of all of the possible preferences for the specified user * This returns a nice flat array of all of the possible preferences for the specified user
*/ */
public static function get_all($user_id) { public static function get_all($user_id)
{
$user_id = Dba::escape($user_id); $user_id = Dba::escape($user_id);
if ($user_id != '-1') { if ($user_id != '-1') {
@ -247,8 +243,8 @@ class Preference {
* This inserts a new preference into the preference table * This inserts a new preference into the preference table
* it does NOT sync up the users, that should be done independtly * it does NOT sync up the users, that should be done independtly
*/ */
public static function insert($name,$description,$default,$level,$type,$catagory) { public static function insert($name,$description,$default,$level,$type,$catagory)
{
// Clean em up // Clean em up
$name = Dba::escape($name); $name = Dba::escape($name);
$description = Dba::escape($description); $description = Dba::escape($description);
@ -271,14 +267,13 @@ class Preference {
* delete * delete
* This deletes the specified preference, a name or a ID can be passed * This deletes the specified preference, a name or a ID can be passed
*/ */
public static function delete($preference) { public static function delete($preference)
{
// First prepare // First prepare
if (!is_numeric($preference)) { if (!is_numeric($preference)) {
$name = Dba::escape($preference); $name = Dba::escape($preference);
$sql = "DELETE FROM `preference` WHERE `name`='$name'"; $sql = "DELETE FROM `preference` WHERE `name`='$name'";
} } else {
else {
$id = Dba::escape($preference); $id = Dba::escape($preference);
$sql = "DELETE FROM `preference` WHERE `id`='$id'"; $sql = "DELETE FROM `preference` WHERE `id`='$id'";
} }
@ -293,7 +288,8 @@ class Preference {
* rename * rename
* This renames a preference in the database * This renames a preference in the database
*/ */
public static function rename($old, $new) { public static function rename($old, $new)
{
$old = Dba::escape($old); $old = Dba::escape($old);
$new = Dba::escape($new); $new = Dba::escape($new);
@ -305,8 +301,8 @@ class Preference {
* rebuild_preferences * rebuild_preferences
* This removes any garbage and then adds back in anything missing preferences wise * This removes any garbage and then adds back in anything missing preferences wise
*/ */
public static function rebuild_preferences() { public static function rebuild_preferences()
{
// First remove garbage // First remove garbage
$sql = "DELETE FROM `user_preference` USING `user_preference` LEFT JOIN `preference` ON `preference`.`id`=`user_preference`.`preference` " . $sql = "DELETE FROM `user_preference` USING `user_preference` LEFT JOIN `preference` ON `preference`.`id`=`user_preference`.`preference` " .
"WHERE `preference`.`id` IS NULL"; "WHERE `preference`.`id` IS NULL";
@ -323,13 +319,14 @@ class Preference {
* This takes the preferences, explodes what needs to * This takes the preferences, explodes what needs to
* become an array and boolean everythings * become an array and boolean everythings
*/ */
public static function fix_preferences($results) { public static function fix_preferences($results)
{
$arrays = array('auth_methods', 'getid3_tag_order', $arrays = array('auth_methods', 'getid3_tag_order',
'metadata_order', 'art_order', 'amazon_base_urls'); 'metadata_order', 'art_order', 'amazon_base_urls');
foreach ($arrays as $item) { foreach ($arrays as $item) {
$results[$item] = trim($results[$item]) $results[$item] = trim($results[$item])
? explode(',', $results[$item]) ? explode(',', $results[$item])
: array(); : array();
} }
@ -348,8 +345,8 @@ class Preference {
* load_from_session * load_from_session
* This loads the preferences from the session rather then creating a connection to the database * This loads the preferences from the session rather then creating a connection to the database
*/ */
public static function load_from_session($uid=-1) { public static function load_from_session($uid=-1)
{
if (is_array($_SESSION['userdata']['preferences']) AND $_SESSION['userdata']['uid'] == $uid) { if (is_array($_SESSION['userdata']['preferences']) AND $_SESSION['userdata']['uid'] == $uid) {
Config::set_by_array($_SESSION['userdata']['preferences'], true); Config::set_by_array($_SESSION['userdata']['preferences'], true);
return true; return true;
@ -364,8 +361,8 @@ class Preference {
* This clears the users preferences, this is done whenever modifications are made to the preferences * This clears the users preferences, this is done whenever modifications are made to the preferences
* or the admin resets something * or the admin resets something
*/ */
public static function clear_from_session() { public static function clear_from_session()
{
unset($_SESSION['userdata']['preferences']); unset($_SESSION['userdata']['preferences']);
} // clear_from_session } // clear_from_session
@ -376,8 +373,8 @@ class Preference {
* This is currently only used by the debug view, could be used other places.. wouldn't be a half * This is currently only used by the debug view, could be used other places.. wouldn't be a half
* bad idea * bad idea
*/ */
public static function is_boolean($key) { public static function is_boolean($key)
{
$boolean_array = array('session_cookiesecure','require_session', $boolean_array = array('session_cookiesecure','require_session',
'access_control','require_localnet_session', 'access_control','require_localnet_session',
'downsample_remote','track_user_ip', 'downsample_remote','track_user_ip',
@ -405,8 +402,8 @@ class Preference {
* This grabs the preferences and then loads them into conf it should be run on page load * This grabs the preferences and then loads them into conf it should be run on page load
* to initialize the needed variables * to initialize the needed variables
*/ */
public static function init() { public static function init()
{
$user_id = $GLOBALS['user']->id ? Dba::escape($GLOBALS['user']->id) : '-1'; $user_id = $GLOBALS['user']->id ? Dba::escape($GLOBALS['user']->id) : '-1';
// First go ahead and try to load it from the preferences // First go ahead and try to load it from the preferences

View file

@ -28,8 +28,8 @@
* for newsearch, and they should be merged if possible. * for newsearch, and they should be merged if possible.
* *
*/ */
class Query { class Query
{
public $id; public $id;
public $catalog; public $catalog;
@ -43,9 +43,10 @@ class Query {
* constructor * constructor
* This should be called * This should be called
*/ */
public function __construct($id = null, $cached = true) { public function __construct($id = null, $cached = true)
{
$sid = session_id(); $sid = session_id();
if (is_null($id)) { if (is_null($id)) {
$this->reset(); $this->reset();
if ($cached) { if ($cached) {
@ -55,9 +56,8 @@ class Query {
'VALUES(?, ?)'; 'VALUES(?, ?)';
$db_results = Dba::write($sql, array($sid, $data)); $db_results = Dba::write($sql, array($sid, $data));
$this->id = Dba::insert_id(); $this->id = Dba::insert_id();
} } else {
else {
$this->id = 'nocache'; $this->id = 'nocache';
} }
return true; return true;
@ -84,7 +84,8 @@ class Query {
* Automatically called when the class is loaded. * Automatically called when the class is loaded.
* Populate static arrays if necessary * Populate static arrays if necessary
*/ */
public static function _auto_init() { public static function _auto_init()
{
if (is_array(self::$allowed_filters)) { if (is_array(self::$allowed_filters)) {
return true; return true;
} }
@ -215,10 +216,11 @@ class Query {
} }
/** /**
* gc * gc
* This cleans old data out of the table * This cleans old data out of the table
*/ */
public static function gc() { public static function gc()
{
$sql = 'DELETE FROM `tmp_browse` USING `tmp_browse` LEFT JOIN ' . $sql = 'DELETE FROM `tmp_browse` USING `tmp_browse` LEFT JOIN ' .
'`session` ON `session`.`id` = `tmp_browse`.`sid` ' . '`session` ON `session`.`id` = `tmp_browse`.`sid` ' .
'WHERE `session`.`id` IS NULL'; 'WHERE `session`.`id` IS NULL';
@ -231,7 +233,8 @@ class Query {
* Attempts to produce a more compact representation for large result * Attempts to produce a more compact representation for large result
* sets by collapsing ranges. * sets by collapsing ranges.
*/ */
private static function _serialize($data) { private static function _serialize($data)
{
if (count($data) > 1000) { if (count($data) > 1000) {
$last = -17; $last = -17;
$in_range = false; $in_range = false;
@ -241,13 +244,11 @@ class Query {
if ($id == ($last + 1)) { if ($id == ($last + 1)) {
if ($in_range) { if ($in_range) {
$cooked[$idx][1] = $id; $cooked[$idx][1] = $id;
} } else {
else {
$in_range = true; $in_range = true;
$cooked[$idx] = array($last, $id); $cooked[$idx] = array($last, $id);
} }
} } else {
else {
$in_range = false; $in_range = false;
$idx++; $idx++;
$cooked[$idx] = $id; $cooked[$idx] = $id;
@ -256,11 +257,10 @@ class Query {
} }
$data = json_encode($cooked); $data = json_encode($cooked);
debug_event('Query', 'cooked serialize length: ' . strlen($data), 5); debug_event('Query', 'cooked serialize length: ' . strlen($data), 5);
} } else {
else {
$data = json_encode($data); $data = json_encode($data);
} }
return $data; return $data;
} }
@ -269,16 +269,16 @@ class Query {
* *
* Reverses serialization. * Reverses serialization.
*/ */
private static function _unserialize($data) { private static function _unserialize($data)
{
$raw = array(); $raw = array();
$cooked = json_decode($data); $cooked = json_decode($data);
foreach ($cooked as $grain) { foreach ($cooked as $grain) {
if (is_array($grain)) { if (is_array($grain)) {
foreach(range($grain[0], $grain[1]) as $id) { foreach (range($grain[0], $grain[1]) as $id) {
$raw[] = $id; $raw[] = $id;
} }
} } else {
else {
$raw[] = $grain; $raw[] = $grain;
} }
} }
@ -289,17 +289,15 @@ class Query {
* set_filter * set_filter
* This saves the filter data we pass it. * This saves the filter data we pass it.
*/ */
public function set_filter($key, $value) { public function set_filter($key, $value)
{
switch ($key) { switch ($key) {
case 'tag': case 'tag':
if (is_array($value)) { if (is_array($value)) {
$this->_state['filter'][$key] = $value; $this->_state['filter'][$key] = $value;
} } elseif (is_numeric($value)) {
elseif (is_numeric($value)) {
$this->_state['filter'][$key] = array($value); $this->_state['filter'][$key] = array($value);
} } else {
else {
$this->_state['filter'][$key] = array(); $this->_state['filter'][$key] = array();
} }
break; break;
@ -327,8 +325,7 @@ class Query {
break; break;
case 'playlist_type': case 'playlist_type':
// Must be a content manager to turn this off // Must be a content manager to turn this off
if ($this->_state['filter'][$key] AND Access::check('interface','50')) { unset($this->_state['filter'][$key]); } if ($this->_state['filter'][$key] AND Access::check('interface','50')) { unset($this->_state['filter'][$key]); } else { $this->_state['filter'][$key] = '1'; }
else { $this->_state['filter'][$key] = '1'; }
break; break;
default: default:
// Rien a faire // Rien a faire
@ -349,8 +346,8 @@ class Query {
* Reset everything, this should only be called when we are starting * Reset everything, this should only be called when we are starting
* fresh * fresh
*/ */
public function reset() { public function reset()
{
$this->reset_base(); $this->reset_base();
$this->reset_filters(); $this->reset_filters();
$this->reset_total(); $this->reset_total();
@ -368,8 +365,8 @@ class Query {
* reset_base * reset_base
* this resets the base string * this resets the base string
*/ */
public function reset_base() { public function reset_base()
{
$this->_state['base'] = NULL; $this->_state['base'] = NULL;
} // reset_base } // reset_base
@ -378,8 +375,8 @@ class Query {
* reset_select * reset_select
* This resets the select fields that we've added so far * This resets the select fields that we've added so far
*/ */
public function reset_select() { public function reset_select()
{
$this->_state['select'] = array(); $this->_state['select'] = array();
} // reset_select } // reset_select
@ -388,8 +385,8 @@ class Query {
* reset_having * reset_having
* Null out the having clause * Null out the having clause
*/ */
public function reset_having() { public function reset_having()
{
unset($this->_state['having']); unset($this->_state['having']);
} // reset_having } // reset_having
@ -398,8 +395,8 @@ class Query {
* reset_join * reset_join
* clears the joins if there are any * clears the joins if there are any
*/ */
public function reset_join() { public function reset_join()
{
unset($this->_state['join']); unset($this->_state['join']);
} // reset_join } // reset_join
@ -408,8 +405,8 @@ class Query {
* reset_filter * reset_filter
* This is a wrapper function that resets the filters * This is a wrapper function that resets the filters
*/ */
public function reset_filters() { public function reset_filters()
{
$this->_state['filter'] = array(); $this->_state['filter'] = array();
} // reset_filters } // reset_filters
@ -418,8 +415,8 @@ class Query {
* reset_total * reset_total
* This resets the total for the browse type * This resets the total for the browse type
*/ */
public function reset_total() { public function reset_total()
{
unset($this->_state['total']); unset($this->_state['total']);
} // reset_total } // reset_total
@ -428,11 +425,11 @@ class Query {
* get_filter * get_filter
* returns the specified filter value * returns the specified filter value
*/ */
public function get_filter($key) { public function get_filter($key)
{
// Simple enough, but if we ever move this crap // Simple enough, but if we ever move this crap
// If we ever move this crap what? // If we ever move this crap what?
return isset($this->_state['filter'][$key]) return isset($this->_state['filter'][$key])
? $this->_state['filter'][$key] ? $this->_state['filter'][$key]
: false; : false;
@ -442,8 +439,8 @@ class Query {
* get_start * get_start
* This returns the current value of the start * This returns the current value of the start
*/ */
public function get_start() { public function get_start()
{
return $this->_state['start']; return $this->_state['start'];
} // get_start } // get_start
@ -452,7 +449,8 @@ class Query {
* get_offset * get_offset
* This returns the current offset * This returns the current offset
*/ */
public function get_offset() { public function get_offset()
{
if ($this->is_static_content()) { if ($this->is_static_content()) {
return $this->get_total(); return $this->get_total();
} }
@ -464,7 +462,8 @@ class Query {
* set_total * set_total
* This sets the total number of objects * This sets the total number of objects
*/ */
public function set_total($total) { public function set_total($total)
{
$this->_state['total'] = $total; $this->_state['total'] = $total;
} }
@ -474,8 +473,8 @@ class Query {
* If it's already cached used it. if they pass us an array then use * If it's already cached used it. if they pass us an array then use
* that. * that.
*/ */
public function get_total($objects = null) { public function get_total($objects = null)
{
// If they pass something then just return that // If they pass something then just return that
if (is_array($objects) and !$this->is_simple()) { if (is_array($objects) and !$this->is_simple()) {
return count($objects); return count($objects);
@ -497,11 +496,12 @@ class Query {
/** /**
* get_allowed_filters * get_allowed_filters
* This returns an array of the allowed filters based on the type of * This returns an array of the allowed filters based on the type of
* object we are working with, this is used to display the 'filter' * object we are working with, this is used to display the 'filter'
* sidebar stuff. * sidebar stuff.
*/ */
public static function get_allowed_filters($type) { public static function get_allowed_filters($type)
{
return isset(self::$allowed_filters[$type]) return isset(self::$allowed_filters[$type])
? self::$allowed_filters[$type] ? self::$allowed_filters[$type]
: array(); : array();
@ -513,9 +513,9 @@ class Query {
* we do this here so we only have to maintain a single whitelist * we do this here so we only have to maintain a single whitelist
* and if I want to change the location I only have to do it here * and if I want to change the location I only have to do it here
*/ */
public function set_type($type) { public function set_type($type)
{
switch($type) { switch ($type) {
case 'user': case 'user':
case 'video': case 'video':
case 'playlist': case 'playlist':
@ -545,8 +545,8 @@ class Query {
* get_type * get_type
* This returns the type of the browse we currently are using * This returns the type of the browse we currently are using
*/ */
public function get_type() { public function get_type()
{
return $this->_state['type']; return $this->_state['type'];
} // get_type } // get_type
@ -555,8 +555,8 @@ class Query {
* set_sort * set_sort
* This sets the current sort(s) * This sets the current sort(s)
*/ */
public function set_sort($sort,$order='') { public function set_sort($sort,$order='')
{
// If it's not in our list, smeg off! // If it's not in our list, smeg off!
if (!in_array($sort, self::$allowed_sorts[$this->get_type()])) { if (!in_array($sort, self::$allowed_sorts[$this->get_type()])) {
return false; return false;
@ -566,13 +566,11 @@ class Query {
$order = ($order == 'DESC') ? 'DESC' : 'ASC'; $order = ($order == 'DESC') ? 'DESC' : 'ASC';
$this->_state['sort'] = array(); $this->_state['sort'] = array();
$this->_state['sort'][$sort] = $order; $this->_state['sort'][$sort] = $order;
} } elseif ($this->_state['sort'][$sort] == 'DESC') {
elseif ($this->_state['sort'][$sort] == 'DESC') {
// Reset it till I can figure out how to interface the hotness // Reset it till I can figure out how to interface the hotness
$this->_state['sort'] = array(); $this->_state['sort'] = array();
$this->_state['sort'][$sort] = 'ASC'; $this->_state['sort'][$sort] = 'ASC';
} } else {
else {
// Reset it till I can figure out how to interface the hotness // Reset it till I can figure out how to interface the hotness
$this->_state['sort'] = array(); $this->_state['sort'] = array();
$this->_state['sort'][$sort] = 'DESC'; $this->_state['sort'][$sort] = 'DESC';
@ -586,25 +584,26 @@ class Query {
* set_offset * set_offset
* This sets the current offset of this query * This sets the current offset of this query
*/ */
public function set_offset($offset) { public function set_offset($offset)
{
$this->_state['offset'] = abs($offset); $this->_state['offset'] = abs($offset);
} // set_offset } // set_offset
public function set_catalog( $catalog_number ) { public function set_catalog( $catalog_number )
{
$this->catalog = $catalog_number; $this->catalog = $catalog_number;
debug_event("Catalog", "set catalog id: " . $this->catalog, "5"); debug_event("Catalog", "set catalog id: " . $this->catalog, "5");
} }
/** /**
* set_select * set_select
* This appends more information to the select part of the SQL * This appends more information to the select part of the SQL
* statement, we're going to move to the %%SELECT%% style queries, as I * statement, we're going to move to the %%SELECT%% style queries, as I
* think it's the only way to do this... * think it's the only way to do this...
*/ */
public function set_select($field) { public function set_select($field)
{
$this->_state['select'][] = $field; $this->_state['select'][] = $field;
} // set_select } // set_select
@ -613,8 +612,8 @@ class Query {
* set_join * set_join
* This sets the joins for the current browse object * This sets the joins for the current browse object
*/ */
public function set_join($type, $table, $source, $dest, $priority) { public function set_join($type, $table, $source, $dest, $priority)
{
$this->_state['join'][$priority][$table] = strtoupper($type) . ' JOIN ' . $table . ' ON ' . $source . '=' . $dest; $this->_state['join'][$priority][$table] = strtoupper($type) . ' JOIN ' . $table . ' ON ' . $source . '=' . $dest;
} // set_join } // set_join
@ -624,8 +623,8 @@ class Query {
* This sets the "HAVING" part of the query, we can only have one.. * This sets the "HAVING" part of the query, we can only have one..
* god this is ugly * god this is ugly
*/ */
public function set_having($condition) { public function set_having($condition)
{
$this->_state['having'] = $condition; $this->_state['having'] = $condition;
} // set_having } // set_having
@ -636,9 +635,8 @@ class Query {
* We need to store this in the session so that it can be pulled * We need to store this in the session so that it can be pulled
* back, if they hit the back button * back, if they hit the back button
*/ */
public function set_start($start) { public function set_start($start)
{
$start = intval($start); $start = intval($start);
if (!$this->is_static_content()) { if (!$this->is_static_content()) {
@ -652,8 +650,8 @@ class Query {
* This sets the current browse object to a 'simple' browse method * This sets the current browse object to a 'simple' browse method
* which means use the base query provided and expand from there * which means use the base query provided and expand from there
*/ */
public function set_is_simple($value) { public function set_is_simple($value)
{
$value = make_bool($value); $value = make_bool($value);
$this->_state['simple'] = $value; $this->_state['simple'] = $value;
@ -665,8 +663,8 @@ class Query {
* should be static, if they are then content filtering/altering * should be static, if they are then content filtering/altering
* methods will be skipped * methods will be skipped
*/ */
public function set_static_content($value) { public function set_static_content($value)
{
$value = make_bool($value); $value = make_bool($value);
// We want to start at 0 if it's static // We want to start at 0 if it's static
@ -678,7 +676,8 @@ class Query {
} // set_static_content } // set_static_content
public function is_static_content() { public function is_static_content()
{
return $this->_state['static']; return $this->_state['static'];
} }
@ -686,19 +685,19 @@ class Query {
* is_simple * is_simple
* This returns whether or not the current browse type is set to static. * This returns whether or not the current browse type is set to static.
*/ */
public function is_simple() { public function is_simple()
{
return $this->_state['simple']; return $this->_state['simple'];
} // is_simple } // is_simple
/** /**
* get_saved * get_saved
* This looks in the session for the saved stuff and returns what it * This looks in the session for the saved stuff and returns what it
* finds. * finds.
*/ */
public function get_saved() { public function get_saved()
{
// See if we have it in the local cache first // See if we have it in the local cache first
if (is_array($this->_cache)) { if (is_array($this->_cache)) {
return $this->_cache; return $this->_cache;
@ -713,8 +712,7 @@ class Query {
$this->_cache = self::_unserialize($row['object_data']); $this->_cache = self::_unserialize($row['object_data']);
return $this->_cache; return $this->_cache;
} } else {
else {
$objects = $this->get_objects(); $objects = $this->get_objects();
} }
@ -728,8 +726,8 @@ class Query {
* currently browsing by it applies the sql and logic based * currently browsing by it applies the sql and logic based
* filters * filters
*/ */
public function get_objects() { public function get_objects()
{
// First we need to get the SQL statement we are going to run // First we need to get the SQL statement we are going to run
// This has to run against any possible filters (dependent on type) // This has to run against any possible filters (dependent on type)
$sql = $this->get_sql(true); $sql = $this->get_sql(true);
@ -760,8 +758,8 @@ class Query {
* set_base_sql * set_base_sql
* This saves the base sql statement we are going to use. * This saves the base sql statement we are going to use.
*/ */
private function set_base_sql($force = false) { private function set_base_sql($force = false)
{
// Only allow it to be set once // Only allow it to be set once
if (strlen($this->_state['base']) && !$force) { return true; } if (strlen($this->_state['base']) && !$force) { return true; }
@ -828,8 +826,8 @@ class Query {
* This returns the selects in a format that is friendly for a sql * This returns the selects in a format that is friendly for a sql
* statement. * statement.
*/ */
private function get_select() { private function get_select()
{
$select_string = implode($this->_state['select'], ", "); $select_string = implode($this->_state['select'], ", ");
return $select_string; return $select_string;
@ -840,8 +838,8 @@ class Query {
* This returns the base sql statement all parsed up, this should be * This returns the base sql statement all parsed up, this should be
* called after all set operations. * called after all set operations.
*/ */
private function get_base_sql() { private function get_base_sql()
{
$sql = str_replace("%%SELECT%%", $this->get_select(), $this->_state['base']); $sql = str_replace("%%SELECT%%", $this->get_select(), $this->_state['base']);
return $sql; return $sql;
@ -851,15 +849,15 @@ class Query {
* get_filter_sql * get_filter_sql
* This returns the filter part of the sql statement * This returns the filter part of the sql statement
*/ */
private function get_filter_sql() { private function get_filter_sql()
{
if (!is_array($this->_state['filter'])) { if (!is_array($this->_state['filter'])) {
return ''; return '';
} }
$sql = "WHERE 1=1 AND "; $sql = "WHERE 1=1 AND ";
foreach ($this->_state['filter'] foreach ($this->_state['filter']
as $key => $value) { as $key => $value) {
$sql .= $this->sql_filter($key, $value); $sql .= $this->sql_filter($key, $value);
@ -875,8 +873,8 @@ class Query {
* get_sort_sql * get_sort_sql
* Returns the sort sql part * Returns the sort sql part
*/ */
private function get_sort_sql() { private function get_sort_sql()
{
if (!is_array($this->_state['sort'])) { if (!is_array($this->_state['sort'])) {
return ''; return '';
} }
@ -899,8 +897,8 @@ class Query {
* get_limit_sql * get_limit_sql
* This returns the limit part of the sql statement * This returns the limit part of the sql statement
*/ */
private function get_limit_sql() { private function get_limit_sql()
{
if (!$this->is_simple()) { return ''; } if (!$this->is_simple()) { return ''; }
$sql = ' LIMIT ' . intval($this->get_start()) . ',' . intval($this->get_offset()); $sql = ' LIMIT ' . intval($this->get_start()) . ',' . intval($this->get_offset());
@ -913,8 +911,8 @@ class Query {
* get_join_sql * get_join_sql
* This returns the joins that this browse may need to work correctly * This returns the joins that this browse may need to work correctly
*/ */
private function get_join_sql() { private function get_join_sql()
{
if (!is_array($this->_state['join'])) { if (!is_array($this->_state['join'])) {
return ''; return '';
} }
@ -935,8 +933,8 @@ class Query {
* get_having_sql * get_having_sql
* this returns the having sql stuff, if we've got anything * this returns the having sql stuff, if we've got anything
*/ */
public function get_having_sql() { public function get_having_sql()
{
$sql = $this->_state['having']; $sql = $this->_state['having'];
return $sql; return $sql;
@ -949,8 +947,8 @@ class Query {
* every time we get the objects because it depends on the filters and * every time we get the objects because it depends on the filters and
* the type of object we are currently browsing. * the type of object we are currently browsing.
*/ */
public function get_sql($limit = true) { public function get_sql($limit = true)
{
$sql = $this->get_base_sql(); $sql = $this->get_base_sql();
$filter_sql = $this->get_filter_sql(); $filter_sql = $this->get_filter_sql();
@ -959,8 +957,8 @@ class Query {
$order_sql = $this->get_sort_sql(); $order_sql = $this->get_sort_sql();
$limit_sql = $limit ? $this->get_limit_sql() : ''; $limit_sql = $limit ? $this->get_limit_sql() : '';
$final_sql = $sql . $join_sql . $filter_sql . $having_sql; $final_sql = $sql . $join_sql . $filter_sql . $having_sql;
if( $this->get_type() == 'artist' ) { if ( $this->get_type() == 'artist' ) {
$final_sql .= " GROUP BY `" . $this->get_type() . "`.`name` "; $final_sql .= " GROUP BY `" . $this->get_type() . "`.`name` ";
} }
$final_sql .= $order_sql . $limit_sql; $final_sql .= $order_sql . $limit_sql;
@ -974,8 +972,8 @@ class Query {
* This does some additional work on the results that we've received * This does some additional work on the results that we've received
* before returning them. * before returning them.
*/ */
private function post_process($data) { private function post_process($data)
{
$tags = $this->_state['filter']['tag']; $tags = $this->_state['filter']['tag'];
if (!is_array($tags) || sizeof($tags) < 2) { if (!is_array($tags) || sizeof($tags) < 2) {
@ -985,13 +983,13 @@ class Query {
$tag_count = sizeof($tags); $tag_count = sizeof($tags);
$count = array(); $count = array();
foreach($data as $row) { foreach ($data as $row) {
$count[$row['id']]++; $count[$row['id']]++;
} }
$results = array(); $results = array();
foreach($count as $key => $value) { foreach ($count as $key => $value) {
if ($value >= $tag_count) { if ($value >= $tag_count) {
$results[] = array('id' => $key); $results[] = array('id' => $key);
} }
@ -1007,14 +1005,14 @@ class Query {
* to filter by this name on this type returns the appropriate sql * to filter by this name on this type returns the appropriate sql
* if not returns nothing * if not returns nothing
*/ */
private function sql_filter($filter, $value) { private function sql_filter($filter, $value)
{
$filter_sql = ''; $filter_sql = '';
switch ($this->get_type()) { switch ($this->get_type()) {
case 'song': case 'song':
switch($filter) { switch ($filter) {
case 'tag': case 'tag':
$this->set_join('left', '`tag_map`', '`tag_map`.`object_id`', '`song`.`id`', 100); $this->set_join('left', '`tag_map`', '`tag_map`.`object_id`', '`song`.`id`', 100);
$filter_sql = " `tag_map`.`object_type`='song' AND ("; $filter_sql = " `tag_map`.`object_type`='song' AND (";
@ -1032,7 +1030,7 @@ class Query {
break; break;
case 'starts_with': case 'starts_with':
$filter_sql = " `song`.`title` LIKE '" . Dba::escape($value) . "%' AND "; $filter_sql = " `song`.`title` LIKE '" . Dba::escape($value) . "%' AND ";
if( $this->catalog != 0 ) { if ($this->catalog != 0) {
$filter_sql .= " `song`.`catalog` = '" . $this->catalog . "' AND "; $filter_sql .= " `song`.`catalog` = '" . $this->catalog . "' AND ";
} }
break; break;
@ -1058,7 +1056,7 @@ class Query {
$filter_sql = " `song`.`update_time` <= '" . Dba::escape($value) . "' AND "; $filter_sql = " `song`.`update_time` <= '" . Dba::escape($value) . "' AND ";
break; break;
case 'catalog': case 'catalog':
if($value != 0) { if ($value != 0) {
$filter_sql = " `song`.`catalog` = '$value' AND "; $filter_sql = " `song`.`catalog` = '$value' AND ";
} }
break; break;
@ -1068,7 +1066,7 @@ class Query {
} // end list of sqlable filters } // end list of sqlable filters
break; break;
case 'album': case 'album':
switch($filter) { switch ($filter) {
case 'exact_match': case 'exact_match':
$filter_sql = " `album`.`name` = '" . Dba::escape($value) . "' AND "; $filter_sql = " `album`.`name` = '" . Dba::escape($value) . "' AND ";
break; break;
@ -1078,7 +1076,7 @@ class Query {
case 'starts_with': case 'starts_with':
$this->set_join('left', '`song`', '`album`.`id`', '`song`.`album`', 100); $this->set_join('left', '`song`', '`album`.`id`', '`song`.`album`', 100);
$filter_sql = " `album`.`name` LIKE '" . Dba::escape($value) . "%' AND "; $filter_sql = " `album`.`name` LIKE '" . Dba::escape($value) . "%' AND ";
if( $this->catalog != 0 ) { if ($this->catalog != 0) {
$filter_sql .= "`song`.`catalog` = '" . $this->catalog . "' AND "; $filter_sql .= "`song`.`catalog` = '" . $this->catalog . "' AND ";
} }
break; break;
@ -1094,7 +1092,7 @@ class Query {
$filter_sql = " `song`.`addition_time` >= '" . Dba::escape($value) . "' AND "; $filter_sql = " `song`.`addition_time` >= '" . Dba::escape($value) . "' AND ";
break; break;
case 'catalog': case 'catalog':
if($value != 0) { if ($value != 0) {
$this->set_join('left','`song`','`album`.`id`','`song`.`album`', 100); $this->set_join('left','`song`','`album`.`id`','`song`.`album`', 100);
$this->set_join('left','`catalog`','`song`.`catalog`','`catalog`.`id`', 100); $this->set_join('left','`catalog`','`song`.`catalog`','`catalog`.`id`', 100);
$filter_sql = " (`song`.`catalog` = '$value') AND "; $filter_sql = " (`song`.`catalog` = '$value') AND ";
@ -1114,9 +1112,9 @@ class Query {
} }
break; break;
case 'artist': case 'artist':
switch($filter) { switch ($filter) {
case 'catalog': case 'catalog':
if($value != 0) { if ($value != 0) {
$this->set_join('left','`song`','`artist`.`id`','`song`.`artist`', 100); $this->set_join('left','`song`','`artist`.`id`','`song`.`artist`', 100);
$this->set_join('left','`catalog`','`song`.`catalog`','`catalog`.`id`', 100); $this->set_join('left','`catalog`','`song`.`catalog`','`catalog`.`id`', 100);
$filter_sql = " (`catalog`.`id` = '$value') AND "; $filter_sql = " (`catalog`.`id` = '$value') AND ";
@ -1131,7 +1129,7 @@ class Query {
case 'starts_with': case 'starts_with':
$this->set_join('left', '`song`', '`artist`.`id`', '`song`.`artist`', 100); $this->set_join('left', '`song`', '`artist`.`id`', '`song`.`artist`', 100);
$filter_sql = " `artist`.`name` LIKE '" . Dba::escape($value) . "%' AND "; $filter_sql = " `artist`.`name` LIKE '" . Dba::escape($value) . "%' AND ";
if( $this->catalog != 0 ) { if ($this->catalog != 0) {
$filter_sql .= "`song`.`catalog` = '" . $this->catalog . "' AND "; $filter_sql .= "`song`.`catalog` = '" . $this->catalog . "' AND ";
} }
break; break;
@ -1242,8 +1240,8 @@ class Query {
* these should be limited as they are often intensive and * these should be limited as they are often intensive and
* require additional queries per object... :( * require additional queries per object... :(
*/ */
private function logic_filter($object_id) { private function logic_filter($object_id)
{
return true; return true;
} // logic_filter } // logic_filter
@ -1255,15 +1253,15 @@ class Query {
* a logic based sort that will come later as that's * a logic based sort that will come later as that's
* a lot more complicated * a lot more complicated
*/ */
private function sql_sort($field, $order) { private function sql_sort($field, $order)
{
if ($order != 'DESC') { $order == 'ASC'; } if ($order != 'DESC') { $order == 'ASC'; }
// Depending on the type of browsing we are doing we can apply // Depending on the type of browsing we are doing we can apply
// different filters that apply to different fields // different filters that apply to different fields
switch ($this->get_type()) { switch ($this->get_type()) {
case 'song': case 'song':
switch($field) { switch ($field) {
case 'title'; case 'title';
$sql = "`song`.`title`"; $sql = "`song`.`title`";
break; break;
@ -1290,7 +1288,7 @@ class Query {
} // end switch } // end switch
break; break;
case 'album': case 'album':
switch($field) { switch ($field) {
case 'name': case 'name':
$sql = "`album`.`name` $order, `album`.`disk`"; $sql = "`album`.`name` $order, `album`.`disk`";
break; break;
@ -1406,15 +1404,14 @@ class Query {
* sort method and then re-sorts them This is internally * sort method and then re-sorts them This is internally
* called by the set_sort() function * called by the set_sort() function
*/ */
private function resort_objects() { private function resort_objects()
{
// There are two ways to do this.. the easy way... // There are two ways to do this.. the easy way...
// and the vollmer way, hopefully we don't have to // and the vollmer way, hopefully we don't have to
// do it the vollmer way // do it the vollmer way
if ($this->is_simple()) { if ($this->is_simple()) {
$sql = $this->get_sql(true); $sql = $this->get_sql(true);
} } else {
else {
// FIXME: this is fragile for large browses // FIXME: this is fragile for large browses
// First pull the objects // First pull the objects
$objects = $this->get_saved(); $objects = $this->get_saved();
@ -1464,7 +1461,8 @@ class Query {
* store * store
* This saves the current state to the database * This saves the current state to the database
*/ */
public function store() { public function store()
{
$id = $this->id; $id = $this->id;
if ($id != 'nocache') { if ($id != 'nocache') {
$data = serialize($this->_state); $data = serialize($this->_state);
@ -1478,17 +1476,17 @@ class Query {
/** /**
* save_objects * save_objects
* This takes the full array of object ids, often passed into show and * This takes the full array of object ids, often passed into show and
* if necessary it saves them * if necessary it saves them
*/ */
public function save_objects($object_ids) { public function save_objects($object_ids)
{
// Saving these objects has two operations, one holds it in // Saving these objects has two operations, one holds it in
// a local variable and then second holds it in a row in the // a local variable and then second holds it in a row in the
// tmp_browse table // tmp_browse table
// Only do this if it's not a simple browse // Only do this if it's not a simple browse
if (!$this->is_simple()) { if (!$this->is_simple()) {
$this->_cache = $object_ids; $this->_cache = $object_ids;
$this->set_total(count($object_ids)); $this->set_total(count($object_ids));
$id = $this->id; $id = $this->id;
@ -1510,8 +1508,8 @@ class Query {
* get_state * get_state
* This is a debug only function * This is a debug only function
*/ */
public function get_state() { public function get_state()
{
return $this->_state; return $this->_state;
} // get_state } // get_state

View file

@ -28,8 +28,8 @@
* this can include podcasts or what-have-you * this can include podcasts or what-have-you
* *
*/ */
class Radio extends database_object implements media { class Radio extends database_object implements media
{
/* DB based variables */ /* DB based variables */
public $id; public $id;
public $name; public $name;
@ -43,8 +43,8 @@ class Radio extends database_object implements media {
* Constructor * Constructor
* This takes a flagged.id and then pulls in the information for said flag entry * This takes a flagged.id and then pulls in the information for said flag entry
*/ */
public function __construct($id) { public function __construct($id)
{
$info = $this->get_info($id,'live_stream'); $info = $this->get_info($id,'live_stream');
// Set the vars // Set the vars
@ -59,8 +59,8 @@ class Radio extends database_object implements media {
* This takes the normal data from the database and makes it pretty * This takes the normal data from the database and makes it pretty
* for the users, the new variables are put in f_??? and f_???_link * for the users, the new variables are put in f_??? and f_???_link
*/ */
public function format() { public function format()
{
// Default link used on the rightbar // Default link used on the rightbar
$this->f_link = "<a href=\"$this->url\">$this->name</a>"; $this->f_link = "<a href=\"$this->url\">$this->name</a>";
@ -78,8 +78,8 @@ class Radio extends database_object implements media {
* it depends on a ID element to determine which radio element it * it depends on a ID element to determine which radio element it
* should be updating * should be updating
*/ */
public static function update($data) { public static function update($data)
{
// Verify the incoming data // Verify the incoming data
if (!$data['id']) { if (!$data['id']) {
Error::add('general', T_('Missing ID')); Error::add('general', T_('Missing ID'));
@ -122,8 +122,8 @@ class Radio extends database_object implements media {
* This is a static function that takes a key'd array for input * This is a static function that takes a key'd array for input
* and if everything is good creates the object. * and if everything is good creates the object.
*/ */
public static function create($data) { public static function create($data)
{
// Make sure we've got a name // Make sure we've got a name
if (!strlen($data['name'])) { if (!strlen($data['name'])) {
Error::add('name', T_('Name Required')); Error::add('name', T_('Name Required'));
@ -166,8 +166,8 @@ class Radio extends database_object implements media {
* delete * delete
* This deletes the current object from the database * This deletes the current object from the database
*/ */
public function delete() { public function delete()
{
$id = Dba::escape($this->id); $id = Dba::escape($this->id);
$sql = "DELETE FROM `live_stream` WHERE `id`='$id'"; $sql = "DELETE FROM `live_stream` WHERE `id`='$id'";
@ -181,7 +181,8 @@ class Radio extends database_object implements media {
* get_stream_types * get_stream_types
* This is needed by the media interface * This is needed by the media interface
*/ */
public function get_stream_types() { public function get_stream_types()
{
return array('foreign'); return array('foreign');
} // native_stream } // native_stream
@ -189,8 +190,8 @@ class Radio extends database_object implements media {
* play_url * play_url
* This is needed by the media interface * This is needed by the media interface
*/ */
public static function play_url($oid,$sid='',$force_http='') { public static function play_url($oid,$sid='',$force_http='')
{
$radio = new Radio($oid); $radio = new Radio($oid);
return $radio->url; return $radio->url;
@ -201,21 +202,18 @@ class Radio extends database_object implements media {
* has_flag * has_flag
* This is needed by the media interface * This is needed by the media interface
*/ */
public function has_flag() { public function has_flag()
{
} // has_flag } // has_flag
/** /**
* get_transcode_settings * get_transcode_settings
* *
* This will probably never be implemented * This will probably never be implemented
*/ */
public function get_transcode_settings($target = null) { public function get_transcode_settings($target = null)
{
return false; return false;
} }
} //end of radio class } //end of radio class
?>

View file

@ -28,8 +28,8 @@
* by this class. There isn't a table for this class so most of its functions * by this class. There isn't a table for this class so most of its functions
* are static. * are static.
*/ */
class Random implements media { class Random implements media
{
public $type; public $type;
public $id; public $id;
@ -37,8 +37,8 @@ class Random implements media {
* Constructor * Constructor
* nothing to see here, move along * nothing to see here, move along
*/ */
public function __construct($id) { public function __construct($id)
{
$this->type = Random::get_id_type($id); $this->type = Random::get_id_type($id);
$this->id = intval($id); $this->id = intval($id);
@ -48,8 +48,8 @@ class Random implements media {
* artist * artist
* This returns the ID of a random artist, nothing special here for now * This returns the ID of a random artist, nothing special here for now
*/ */
public static function artist() { public static function artist()
{
$sql = "SELECT `id` FROM `artist` ORDER BY RAND() LIMIT 1"; $sql = "SELECT `id` FROM `artist` ORDER BY RAND() LIMIT 1";
$db_results = Dba::read($sql); $db_results = Dba::read($sql);
@ -64,8 +64,8 @@ class Random implements media {
* This returns a random Playlist with songs little bit of extra * This returns a random Playlist with songs little bit of extra
* logic require * logic require
*/ */
public static function playlist() { public static function playlist()
{
$sql = "SELECT `playlist`.`id` FROM `playlist` LEFT JOIN `playlist_data` " . $sql = "SELECT `playlist`.`id` FROM `playlist` LEFT JOIN `playlist_data` " .
" ON `playlist`.`id`=`playlist_data`.`playlist` WHERE `playlist_data`.`object_id` IS NOT NULL " . " ON `playlist`.`id`=`playlist_data`.`playlist` WHERE `playlist_data`.`object_id` IS NOT NULL " .
" ORDER BY RAND()"; " ORDER BY RAND()";
@ -83,7 +83,8 @@ class Random implements media {
* This generates a random play url based on the passed type * This generates a random play url based on the passed type
* and returns it * and returns it
*/ */
public static function play_url($id) { public static function play_url($id)
{
if (!$type = self::get_id_type($id)) { if (!$type = self::get_id_type($id)) {
return false; return false;
} }
@ -100,8 +101,8 @@ class Random implements media {
* get_single_song * get_single_song
* This returns a single song pulled based on the passed random method * This returns a single song pulled based on the passed random method
*/ */
public static function get_single_song($type) { public static function get_single_song($type)
{
if (!$type = self::validate_type($type)) { if (!$type = self::validate_type($type)) {
return false; return false;
} }
@ -122,8 +123,8 @@ class Random implements media {
* This just randomly picks a song at whim from all catalogs * This just randomly picks a song at whim from all catalogs
* nothing special here... * nothing special here...
*/ */
public static function get_default($limit) { public static function get_default($limit)
{
$results = array(); $results = array();
$sql = "SELECT `id` FROM `song` ORDER BY RAND() LIMIT $limit"; $sql = "SELECT `id` FROM `song` ORDER BY RAND() LIMIT $limit";
@ -142,8 +143,8 @@ class Random implements media {
* This looks at the last album played by the current user and * This looks at the last album played by the current user and
* picks something else in the same album * picks something else in the same album
*/ */
public static function get_album($limit) { public static function get_album($limit)
{
$results = array(); $results = array();
// Get the last album playbed by us // Get the last album playbed by us
@ -168,8 +169,8 @@ class Random implements media {
* This looks at the last artist played and then randomly picks a song from the * This looks at the last artist played and then randomly picks a song from the
* same artist * same artist
*/ */
public static function get_artist($limit) { public static function get_artist($limit)
{
$results = array(); $results = array();
$data = $GLOBALS['user']->get_recently_played('1','artist'); $data = $GLOBALS['user']->get_recently_played('1','artist');
@ -193,16 +194,15 @@ class Random implements media {
* This processes the results of a post from a form and returns an * This processes the results of a post from a form and returns an
* array of song items that were returned from said randomness * array of song items that were returned from said randomness
*/ */
public static function advanced($type, $data) { public static function advanced($type, $data)
{
/* Figure out our object limit */ /* Figure out our object limit */
$limit = intval($data['random']); $limit = intval($data['random']);
// Generate our matchlist // Generate our matchlist
/* If they've passed -1 as limit then get everything */ /* If they've passed -1 as limit then get everything */
if ($data['random'] == "-1") { unset($data['random']); } if ($data['random'] == "-1") { unset($data['random']); } else { $limit_sql = "LIMIT " . Dba::escape($limit); }
else { $limit_sql = "LIMIT " . Dba::escape($limit); }
$search_data = Search::clean_request($data); $search_data = Search::clean_request($data);
@ -338,8 +338,8 @@ class Random implements media {
* get_type_name * get_type_name
* This returns a 'purrty' name for the different random types * This returns a 'purrty' name for the different random types
*/ */
public static function get_type_name($type) { public static function get_type_name($type)
{
switch ($type) { switch ($type) {
case 'album': case 'album':
return T_('Related Album'); return T_('Related Album');
@ -363,8 +363,8 @@ class Random implements media {
* MOTHER OF PEARL THIS MAKES BABY JESUS CRY * MOTHER OF PEARL THIS MAKES BABY JESUS CRY
* HACK HACK HACK HACK HACK HACK HACK HACK * HACK HACK HACK HACK HACK HACK HACK HACK
*/ */
public static function get_type_id($type) { public static function get_type_id($type)
{
switch ($type) { switch ($type) {
case 'album': case 'album':
return '1'; return '1';
@ -388,8 +388,8 @@ class Random implements media {
* HACK HACK HACK HACK HACK HACK HACK * HACK HACK HACK HACK HACK HACK HACK
* Can you tell I don't like this code? * Can you tell I don't like this code?
*/ */
public static function get_id_type($id) { public static function get_id_type($id)
{
switch ($id) { switch ($id) {
case '1': case '1':
return 'album'; return 'album';
@ -411,8 +411,8 @@ class Random implements media {
* validate_type * validate_type
* this validates the random type * this validates the random type
*/ */
public static function validate_type($type) { public static function validate_type($type)
{
switch ($type) { switch ($type) {
case 'default': case 'default':
case 'genre': case 'genre':
@ -433,5 +433,3 @@ class Random implements media {
public function format() { } public function format() { }
} //end of random class } //end of random class
?>

View file

@ -26,8 +26,8 @@
* This tracks ratings for songs, albums and artists. * This tracks ratings for songs, albums and artists.
* *
*/ */
class Rating extends database_object { class Rating extends database_object
{
// Public variables // Public variables
public $id; // The ID of the object rated public $id; // The ID of the object rated
public $type; // The type of object we want public $type; // The type of object we want
@ -37,8 +37,8 @@ class Rating extends database_object {
* This is run every time a new object is created, and requires * This is run every time a new object is created, and requires
* the id and type of object that we need to pull the rating for * the id and type of object that we need to pull the rating for
*/ */
public function __construct($id, $type) { public function __construct($id, $type)
{
$this->id = intval($id); $this->id = intval($id);
$this->type = $type; $this->type = $type;
@ -51,19 +51,20 @@ class Rating extends database_object {
* *
* Remove ratings for items that no longer exist. * Remove ratings for items that no longer exist.
*/ */
public static function gc() { public static function gc()
foreach(array('song', 'album', 'artist', 'video') as $object_type) { {
foreach (array('song', 'album', 'artist', 'video') as $object_type) {
Dba::write("DELETE FROM `rating` USING `rating` LEFT JOIN `$object_type` ON `$object_type`.`id` = `rating`.`object_id` WHERE `object_type` = '$object_type' AND `$object_type`.`id` IS NULL"); Dba::write("DELETE FROM `rating` USING `rating` LEFT JOIN `$object_type` ON `$object_type`.`id` = `rating`.`object_id` WHERE `object_type` = '$object_type' AND `$object_type`.`id` IS NULL");
} }
} }
/** /**
* build_cache * build_cache
* This attempts to get everything we'll need for this page load in a * This attempts to get everything we'll need for this page load in a
* single query, saving on connection overhead * single query, saving on connection overhead
*/ */
public static function build_cache($type, $ids) { public static function build_cache($type, $ids)
{
if (!is_array($ids) OR !count($ids)) { return false; } if (!is_array($ids) OR !count($ids)) { return false; }
$ratings = array(); $ratings = array();
@ -92,8 +93,7 @@ class Rating extends database_object {
// First store the user-specific rating // First store the user-specific rating
if (!isset($user_ratings[$id])) { if (!isset($user_ratings[$id])) {
$rating = 0; $rating = 0;
} } else {
else {
$rating = intval($user_ratings[$id]); $rating = intval($user_ratings[$id]);
} }
parent::add_to_cache('rating_' . $type . '_user' . $GLOBALS['user']->id, $id, $rating); parent::add_to_cache('rating_' . $type . '_user' . $GLOBALS['user']->id, $id, $rating);
@ -101,8 +101,7 @@ class Rating extends database_object {
// Then store the average // Then store the average
if (!isset($ratings[$id])) { if (!isset($ratings[$id])) {
$rating = 0; $rating = 0;
} } else {
else {
$rating = round($ratings[$id], 1); $rating = round($ratings[$id], 1);
} }
parent::add_to_cache('rating_' . $type . '_all', $id, $rating); parent::add_to_cache('rating_' . $type . '_all', $id, $rating);
@ -117,12 +116,12 @@ class Rating extends database_object {
* Get a user's rating. If no userid is passed in, we use the currently * Get a user's rating. If no userid is passed in, we use the currently
* logged in user. * logged in user.
*/ */
public function get_user_rating($user_id = null) { public function get_user_rating($user_id = null)
{
if (is_null($user_id)) { if (is_null($user_id)) {
$user_id = $GLOBALS['user']->id; $user_id = $GLOBALS['user']->id;
} }
$key = 'rating_' . $type . '_user' . $user_id; $key = 'rating_' . $type . '_user' . $user_id;
if (parent::is_cached($key, $this->id)) { if (parent::is_cached($key, $this->id)) {
return parent::get_from_cache($key, $this->id); return parent::get_from_cache($key, $this->id);
@ -148,8 +147,8 @@ class Rating extends database_object {
* Get the floored average rating of what everyone has rated this object * Get the floored average rating of what everyone has rated this object
* as. This is shown if there is no personal rating. * as. This is shown if there is no personal rating.
*/ */
public function get_average_rating() { public function get_average_rating()
{
if (parent::is_cached('rating_' . $type . '_all', $id)) { if (parent::is_cached('rating_' . $type . '_all', $id)) {
return parent::get_from_cache('rating_' . $type . '_user', $id); return parent::get_from_cache('rating_' . $type . '_user', $id);
} }
@ -159,18 +158,18 @@ class Rating extends database_object {
$db_results = Dba::read($sql, array($this->id, $this->type)); $db_results = Dba::read($sql, array($this->id, $this->type));
$results = Dba::fetch_assoc($db_results); $results = Dba::fetch_assoc($db_results);
parent::add_to_cache('rating_' . $type . '_all', $id, $results['rating']); parent::add_to_cache('rating_' . $type . '_all', $id, $results['rating']);
return $results['rating']; return $results['rating'];
} // get_average_rating } // get_average_rating
/** /**
* get_highest * get_highest
* Get objects with the highest average rating. * Get objects with the highest average rating.
*/ */
public static function get_highest($type, $count='', $offset='') { public static function get_highest($type, $count='', $offset='')
{
if (!$count) { if (!$count) {
$count = Config::get('popular_threshold'); $count = Config::get('popular_threshold');
} }
@ -194,7 +193,7 @@ class Rating extends database_object {
} }
return $results; return $results;
} }
/** /**
@ -202,8 +201,8 @@ class Rating extends database_object {
* This function sets the rating for the current object. * This function sets the rating for the current object.
* If no userid is passed in, we use the currently logged in user. * If no userid is passed in, we use the currently logged in user.
*/ */
public function set_rating($rating, $user_id = null) { public function set_rating($rating, $user_id = null)
{
if (is_null($user_id)) { if (is_null($user_id)) {
$user_id = $GLOBALS['user']->id; $user_id = $GLOBALS['user']->id;
} }
@ -218,8 +217,7 @@ class Rating extends database_object {
"`object_type` = ? AND " . "`object_type` = ? AND " .
"`user` = ?"; "`user` = ?";
$params = array($this->id, $this->type, $user_id); $params = array($this->id, $this->type, $user_id);
} } else {
else {
$sql = "REPLACE INTO `rating` " . $sql = "REPLACE INTO `rating` " .
"(`object_id`, `object_type`, `rating`, `user`) " . "(`object_id`, `object_type`, `rating`, `user`) " .
"VALUES (?, ?, ?, ?)"; "VALUES (?, ?, ?, ?)";
@ -242,11 +240,11 @@ class Rating extends database_object {
/** /**
* show * show
* This takes an id and a type and displays the rating if ratings are * This takes an id and a type and displays the rating if ratings are
* enabled. If $static is true, the rating won't be editable. * enabled. If $static is true, the rating won't be editable.
*/ */
public static function show($object_id, $type, $static=false) { public static function show($object_id, $type, $static=false)
{
// If ratings aren't enabled don't do anything // If ratings aren't enabled don't do anything
if (!Config::get('ratings')) { return false; } if (!Config::get('ratings')) { return false; }
@ -254,12 +252,10 @@ class Rating extends database_object {
if ($static) { if ($static) {
require Config::get('prefix') . '/templates/show_static_object_rating.inc.php'; require Config::get('prefix') . '/templates/show_static_object_rating.inc.php';
} } else {
else {
require Config::get('prefix') . '/templates/show_object_rating.inc.php'; require Config::get('prefix') . '/templates/show_object_rating.inc.php';
} }
} // show } // show
} //end rating class } //end rating class
?>

View file

@ -20,13 +20,14 @@
* *
*/ */
class Recommendation { class Recommendation
{
/** /**
* Constructor * Constructor
* Not on my watch, boyo. * Not on my watch, boyo.
*/ */
private function __construct() { private function __construct()
{
return false; return false;
} //constructor } //constructor
@ -34,14 +35,15 @@ class Recommendation {
* get_lastfm_results * get_lastfm_results
* Runs a last.fm query and returns the parsed results * Runs a last.fm query and returns the parsed results
*/ */
private static function get_lastfm_results($method, $query) { private static function get_lastfm_results($method, $query)
{
$api_key = Config::get('lastfm_api_key'); $api_key = Config::get('lastfm_api_key');
$api_base = "http://ws.audioscrobbler.com/2.0/?method="; $api_base = "http://ws.audioscrobbler.com/2.0/?method=";
$url = $api_base . $method . '&api_key=' . $api_key . '&' . $query; $url = $api_base . $method . '&api_key=' . $api_key . '&' . $query;
debug_event('Recommendation', 'search url : ' . $url, 5); debug_event('Recommendation', 'search url : ' . $url, 5);
$snoopy = new Snoopy(); $snoopy = new Snoopy();
if(Config::get('proxy_host') AND Config::get('proxy_port')) { if (Config::get('proxy_host') AND Config::get('proxy_port')) {
$snoopy->proxy_user = Config::get('proxy_host'); $snoopy->proxy_user = Config::get('proxy_host');
$snoopy->proxy_port = Config::get('proxy_port'); $snoopy->proxy_port = Config::get('proxy_port');
$snoopy->proxy_user = Config::get('proxy_user'); $snoopy->proxy_user = Config::get('proxy_user');
@ -49,7 +51,7 @@ class Recommendation {
} }
$snoopy->fetch($url); $snoopy->fetch($url);
$content = $snoopy->results; $content = $snoopy->results;
return simplexml_load_string($content); return simplexml_load_string($content);
} // get_lastfm_results } // get_lastfm_results
@ -57,20 +59,20 @@ class Recommendation {
* get_songs_like * get_songs_like
* Returns a list of similar songs * Returns a list of similar songs
*/ */
public static function get_songs_like($song_id, $limit = 5, $local_only = true) { public static function get_songs_like($song_id, $limit = 5, $local_only = true)
{
$song = new Song($song_id); $song = new Song($song_id);
if (isset($song->mbid)) { if (isset($song->mbid)) {
$query = 'mbid=' . rawurlencode($song->mbid); $query = 'mbid=' . rawurlencode($song->mbid);
} } else {
else {
$query = 'track=' . rawurlencode($song->title); $query = 'track=' . rawurlencode($song->title);
} }
if ($limit && !$local_only) { if ($limit && !$local_only) {
$query .= "&limit=$limit"; $query .= "&limit=$limit";
} }
$xml = self::get_lastfm_results('track.getsimilar', $query); $xml = self::get_lastfm_results('track.getsimilar', $query);
foreach ($xml->similartracks->children() as $child) { foreach ($xml->similartracks->children() as $child) {
@ -84,11 +86,11 @@ class Recommendation {
$sql = "SELECT `song`.`id` FROM `song` " . $sql = "SELECT `song`.`id` FROM `song` " .
"LEFT JOIN `artist` ON " . "LEFT JOIN `artist` ON " .
"`song`.`artist`=`artist`.`id` WHERE " . "`song`.`artist`=`artist`.`id` WHERE " .
"`song`.`title`='" . Dba::escape($name) . "`song`.`title`='" . Dba::escape($name) .
"' AND `artist`.`name`='$s_artist_name'"; "' AND `artist`.`name`='$s_artist_name'";
$db_result = Dba::read($sql); $db_result = Dba::read($sql);
if ($result = Dba::fetch_assoc($db_result)) { if ($result = Dba::fetch_assoc($db_result)) {
$local_id = $result['id']; $local_id = $result['id'];
} }
@ -102,8 +104,7 @@ class Recommendation {
'artist' => $artist_name 'artist' => $artist_name
); );
} }
} } else {
else {
debug_event('Recommendation', "$name matched local song $local_id", 5); debug_event('Recommendation', "$name matched local song $local_id", 5);
$results[] = array( $results[] = array(
'id' => $local_id, 'id' => $local_id,
@ -127,7 +128,8 @@ class Recommendation {
* get_artists_like * get_artists_like
* Returns a list of similar artists * Returns a list of similar artists
*/ */
public static function get_artists_like($artist_id, $limit = 5, $local_only = true) { public static function get_artists_like($artist_id, $limit = 5, $local_only = true)
{
$artist = new Artist($artist_id); $artist = new Artist($artist_id);
$query = 'artist=' . rawurlencode($artist->name); $query = 'artist=' . rawurlencode($artist->name);
@ -135,14 +137,14 @@ class Recommendation {
$query .= "&limit=$limit"; $query .= "&limit=$limit";
} }
$xml = self::get_lastfm_results('artist.getsimilar', $query); $xml = self::get_lastfm_results('artist.getsimilar', $query);
foreach ($xml->similarartists->children() as $child) { foreach ($xml->similarartists->children() as $child) {
$name = $child->name; $name = $child->name;
$local_id = null; $local_id = null;
// First we check by MBID // First we check by MBID
if ((string)$child->mbid) { if ((string) $child->mbid) {
$mbid = Dba::escape($child->mbid); $mbid = Dba::escape($child->mbid);
$sql = "SELECT `id` FROM `artist` WHERE `mbid`='$mbid'"; $sql = "SELECT `id` FROM `artist` WHERE `mbid`='$mbid'";
$db_result = Dba::read($sql); $db_result = Dba::read($sql);
@ -162,7 +164,7 @@ class Recommendation {
$local_id = $result['id']; $local_id = $result['id'];
} }
} }
// Then we give up // Then we give up
if (is_null($local_id)) { if (is_null($local_id)) {
debug_event('Recommendation', "$name did not match any local artist", 5); debug_event('Recommendation', "$name did not match any local artist", 5);
@ -172,8 +174,7 @@ class Recommendation {
'name' => $name 'name' => $name
); );
} }
} } else {
else {
debug_event('Recommendation', "$name matched local artist " . $local_id, 5); debug_event('Recommendation', "$name matched local artist " . $local_id, 5);
$results[] = array( $results[] = array(
'id' => $local_id, 'id' => $local_id,
@ -190,9 +191,8 @@ class Recommendation {
if (isset($results)) { if (isset($results)) {
return $results; return $results;
} }
return false; return false;
} // get_artists_like } // get_artists_like
} // end of recommendation class } // end of recommendation class
?>

View file

@ -26,14 +26,14 @@
* This class handles all the doodlys for the registration * This class handles all the doodlys for the registration
* stuff in Ampache * stuff in Ampache
*/ */
class Registration { class Registration
{
/** /**
* constructor * constructor
* This is what is called when the class is loaded * This is what is called when the class is loaded
*/ */
public function __construct() { public function __construct()
{
// Rien a faire // Rien a faire
} // constructor } // constructor
@ -42,7 +42,8 @@ class Registration {
* send_confirmation * send_confirmation
* This sends the confirmation e-mail for the specified user * This sends the confirmation e-mail for the specified user
*/ */
public static function send_confirmation($username, $fullname, $email, $password, $validation) { public static function send_confirmation($username, $fullname, $email, $password, $validation)
{
$mailer = new Mailer(); $mailer = new Mailer();
// We are the system // We are the system
@ -82,7 +83,7 @@ E-mail: %s
$mailer->send_to_group('admins'); $mailer->send_to_group('admins');
} }
return true; return true;
} // send_confirmation } // send_confirmation
@ -91,8 +92,8 @@ E-mail: %s
* show_agreement * show_agreement
* This shows the registration agreement, /config/registration_agreement.php * This shows the registration agreement, /config/registration_agreement.php
*/ */
public static function show_agreement() { public static function show_agreement()
{
$filename = Config::get('prefix') . '/config/registration_agreement.php'; $filename = Config::get('prefix') . '/config/registration_agreement.php';
if (!file_exists($filename)) { return false; } if (!file_exists($filename)) { return false; }
@ -110,4 +111,3 @@ E-mail: %s
} // show_agreement } // show_agreement
} // end registration class } // end registration class
?>

View file

@ -20,8 +20,8 @@
* *
*/ */
class scrobbler { class scrobbler
{
public $error_msg; public $error_msg;
public $username; public $username;
public $password; public $password;
@ -37,8 +37,8 @@ class scrobbler {
* Constructor * Constructor
* This is the constructer it takes a username and password * This is the constructer it takes a username and password
*/ */
public function __construct($username, $password,$host='',$port='',$url='',$challenge='',$scrobble_host='') { public function __construct($username, $password,$host='',$port='',$url='',$challenge='',$scrobble_host='')
{
$this->error_msg = ''; $this->error_msg = '';
$this->username = trim($username); $this->username = trim($username);
$this->password = trim($password); $this->password = trim($password);
@ -54,8 +54,8 @@ class scrobbler {
/** /**
* get_error_msg * get_error_msg
*/ */
public function get_error_msg() { public function get_error_msg()
{
return $this->error_msg; return $this->error_msg;
} // get_error_msg } // get_error_msg
@ -63,8 +63,8 @@ class scrobbler {
/** /**
* get_queue_count * get_queue_count
*/ */
public function get_queue_count() { public function get_queue_count()
{
return count($this->queued_tracks); return count($this->queued_tracks);
} // get_queue_count } // get_queue_count
@ -74,10 +74,10 @@ class scrobbler {
* This does a handshake with the audioscrobber server it doesn't pass the password, but * This does a handshake with the audioscrobber server it doesn't pass the password, but
* it does pass the username and has a 10 second timeout * it does pass the username and has a 10 second timeout
*/ */
public function handshake() { public function handshake()
{
$as_socket = fsockopen($this->scrobble_host, 80, $errno, $errstr, 2); $as_socket = fsockopen($this->scrobble_host, 80, $errno, $errstr, 2);
if(!$as_socket) { if (!$as_socket) {
$this->error_msg = $errstr; $this->error_msg = $errstr;
return false; return false;
} }
@ -93,40 +93,40 @@ class scrobbler {
fwrite($as_socket, "Accept: */*\r\n\r\n"); fwrite($as_socket, "Accept: */*\r\n\r\n");
$buffer = ''; $buffer = '';
while(!feof($as_socket)) { while (!feof($as_socket)) {
$buffer .= fread($as_socket, 4096); $buffer .= fread($as_socket, 4096);
} }
fclose($as_socket); fclose($as_socket);
$split_response = preg_split("/\r\n\r\n/", $buffer); $split_response = preg_split("/\r\n\r\n/", $buffer);
if(!isset($split_response[1])) { if (!isset($split_response[1])) {
$this->error_msg = 'Did not receive a valid response'; $this->error_msg = 'Did not receive a valid response';
return false; return false;
} }
$response = explode("\n", $split_response[1]); $response = explode("\n", $split_response[1]);
// Handle the fact Libre.FM has extranious values at the start of it's handshake response // Handle the fact Libre.FM has extranious values at the start of it's handshake response
if(is_numeric(trim($response['0']))) { if (is_numeric(trim($response['0']))) {
array_shift($response); array_shift($response);
debug_event('SCROBBLER','Junk in handshake, removing first line',1); debug_event('SCROBBLER','Junk in handshake, removing first line',1);
} }
if(substr($response[0], 0, 6) == 'FAILED') { if (substr($response[0], 0, 6) == 'FAILED') {
$this->error_msg = substr($response[0], 7); $this->error_msg = substr($response[0], 7);
return false; return false;
} }
if(substr($response[0], 0, 7) == 'BADUSER') { if (substr($response[0], 0, 7) == 'BADUSER') {
$this->error_msg = 'Invalid Username'; $this->error_msg = 'Invalid Username';
return false; return false;
} }
if(substr($response[0],0,7) == 'BADTIME') { if (substr($response[0],0,7) == 'BADTIME') {
$this->error_msg = 'Your time is too far off from the server, or your PHP timezone is incorrect'; $this->error_msg = 'Your time is too far off from the server, or your PHP timezone is incorrect';
return false; return false;
} }
if(substr($response[0], 0, 6) == 'UPDATE') { if (substr($response[0], 0, 6) == 'UPDATE') {
$this->error_msg = 'You need to update your client: '.substr($response[0], 7); $this->error_msg = 'You need to update your client: '.substr($response[0], 7);
return false; return false;
} }
if(preg_match('/http:\/\/([^\/]+)\/(.*)$/', $response[3], $matches)) { if (preg_match('/http:\/\/([^\/]+)\/(.*)$/', $response[3], $matches)) {
$host_parts = explode(":",$matches[1]); $host_parts = explode(":",$matches[1]);
$data['submit_host'] = $host_parts[0]; $data['submit_host'] = $host_parts[0];
$data['submit_port'] = $host_parts[1] ? $host_parts[1] : '80'; $data['submit_port'] = $host_parts[1] ? $host_parts[1] : '80';
@ -138,7 +138,7 @@ class scrobbler {
} }
// Remove any extra junk around the challenge // Remove any extra junk around the challenge
$data['challenge'] = trim($response[1]); $data['challenge'] = trim($response[1]);
return $data; return $data;
} // handshake } // handshake
@ -149,8 +149,8 @@ class scrobbler {
* submit the track or talk to LastFM in anyway, kind of useless for our uses but its * submit the track or talk to LastFM in anyway, kind of useless for our uses but its
* here, and that's how it is. * here, and that's how it is.
*/ */
public function queue_track($artist, $album, $title, $timestamp, $length,$track) { public function queue_track($artist, $album, $title, $timestamp, $length,$track)
{
if ($length < 30) { if ($length < 30) {
debug_event('Scrobbler',"Not queuing track, too short",'5'); debug_event('Scrobbler',"Not queuing track, too short",'5');
return false; return false;
@ -174,10 +174,10 @@ class scrobbler {
* This actually talks to LastFM submiting the tracks that are queued up. It * This actually talks to LastFM submiting the tracks that are queued up. It
* passed the md5'd password combinted with the challenge, which is then md5'd * passed the md5'd password combinted with the challenge, which is then md5'd
*/ */
public function submit_tracks() { public function submit_tracks()
{
// Check and make sure that we've got some queued tracks // Check and make sure that we've got some queued tracks
if(!count($this->queued_tracks)) { if (!count($this->queued_tracks)) {
$this->error_msg = "No tracks to submit"; $this->error_msg = "No tracks to submit";
return false; return false;
} }
@ -190,7 +190,7 @@ class scrobbler {
$i = 0; $i = 0;
foreach($this->queued_tracks as $track) { foreach ($this->queued_tracks as $track) {
$query_str .= "a[$i]=".rawurlencode($track['artist'])."&t[$i]=".rawurlencode($track['title'])."&b[$i]=".rawurlencode($track['album'])."&"; $query_str .= "a[$i]=".rawurlencode($track['artist'])."&t[$i]=".rawurlencode($track['title'])."&b[$i]=".rawurlencode($track['album'])."&";
$query_str .= "m[$i]=&l[$i]=".rawurlencode($track['length'])."&i[$i]=".rawurlencode($track['time'])."&"; $query_str .= "m[$i]=&l[$i]=".rawurlencode($track['length'])."&i[$i]=".rawurlencode($track['time'])."&";
$query_str .= "n[$i]=" . rawurlencode($track['track']) . "&o[$i]=P&r[$i]=&"; $query_str .= "n[$i]=" . rawurlencode($track['track']) . "&o[$i]=P&r[$i]=&";
@ -204,7 +204,7 @@ class scrobbler {
$as_socket = fsockopen($this->submit_host, intval($this->submit_port), $errno, $errstr, 2); $as_socket = fsockopen($this->submit_host, intval($this->submit_port), $errno, $errstr, 2);
if(!$as_socket) { if (!$as_socket) {
$this->error_msg = $errstr; $this->error_msg = $errstr;
$this->reset_handshake = true; $this->reset_handshake = true;
return false; return false;
@ -220,33 +220,33 @@ class scrobbler {
fwrite($as_socket, $query_str."\r\n\r\n"); fwrite($as_socket, $query_str."\r\n\r\n");
// Allow us to debug this // Allow us to debug this
debug_event('SCROBBLER','Query String:' . $query_str,6); debug_event('SCROBBLER','Query String:' . $query_str,6);
$buffer = ''; $buffer = '';
while(!feof($as_socket)) { while (!feof($as_socket)) {
$buffer .= fread($as_socket, 8192); $buffer .= fread($as_socket, 8192);
} }
fclose($as_socket); fclose($as_socket);
$split_response = preg_split("/\r\n\r\n/", $buffer); $split_response = preg_split("/\r\n\r\n/", $buffer);
if(!isset($split_response[1])) { if (!isset($split_response[1])) {
$this->error_msg = 'Did not receive a valid response'; $this->error_msg = 'Did not receive a valid response';
$this->reset_handshake = true; $this->reset_handshake = true;
return false; return false;
} }
$response = explode("\n", $split_response[1]); $response = explode("\n", $split_response[1]);
if(!isset($response[0])) { if (!isset($response[0])) {
$this->error_msg = 'Unknown error submitting tracks'. $this->error_msg = 'Unknown error submitting tracks'.
"\nDebug output:\n".$buffer; "\nDebug output:\n".$buffer;
$this->reset_handshake = true; $this->reset_handshake = true;
return false; return false;
} }
if(substr($response[0], 0, 6) == 'FAILED') { if (substr($response[0], 0, 6) == 'FAILED') {
$this->error_msg = $response[0]; $this->error_msg = $response[0];
$this->reset_handshake = true; $this->reset_handshake = true;
return false; return false;
} }
if(substr($response[0], 0, 7) == 'BADAUTH') { if (substr($response[0], 0, 7) == 'BADAUTH') {
$this->error_msg = 'Invalid username/password (' . trim($response[0]) . ')'; $this->error_msg = 'Invalid username/password (' . trim($response[0]) . ')';
return false; return false;
} }
@ -255,7 +255,7 @@ class scrobbler {
$this->reset_handshake = true; $this->reset_handshake = true;
return false; return false;
} }
if(substr($response[0], 0, 2) != 'OK') { if (substr($response[0], 0, 2) != 'OK') {
$this->error_msg = 'Response Not ok, unknown error'. $this->error_msg = 'Response Not ok, unknown error'.
"\nDebug output:\n".$buffer; "\nDebug output:\n".$buffer;
$this->reset_handshake = true; $this->reset_handshake = true;
@ -267,4 +267,3 @@ class scrobbler {
} // submit_tracks } // submit_tracks
} // end audioscrobbler class } // end audioscrobbler class
?>

View file

@ -11,7 +11,7 @@
* *
* 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
@ -25,8 +25,8 @@
* Search-related voodoo. Beware tentacles. * Search-related voodoo. Beware tentacles.
*/ */
class Search extends playlist_object { class Search extends playlist_object
{
public $searchtype; public $searchtype;
public $rules; public $rules;
public $logic_operator = 'AND'; public $logic_operator = 'AND';
@ -38,7 +38,8 @@ class Search extends playlist_object {
/** /**
* constructor * constructor
*/ */
public function __construct($searchtype = 'song', $id = '') { public function __construct($searchtype = 'song', $id = '')
{
$this->searchtype = $searchtype; $this->searchtype = $searchtype;
if ($id) { if ($id) {
$info = $this->get_info($id); $info = $this->get_info($id);
@ -148,14 +149,14 @@ class Search extends playlist_object {
'description' => T_('does not sound like'), 'description' => T_('does not sound like'),
'sql' => 'NOT SOUNDS LIKE' 'sql' => 'NOT SOUNDS LIKE'
); );
$this->basetypes['boolean_numeric'][] = array( $this->basetypes['boolean_numeric'][] = array(
'name' => 'equal', 'name' => 'equal',
'description' => T_('is'), 'description' => T_('is'),
'sql' => '<=>' 'sql' => '<=>'
); );
$this->basetypes['boolean_numeric'][] = array( $this->basetypes['boolean_numeric'][] = array(
'name' => 'ne', 'name' => 'ne',
'description' => T_('is not'), 'description' => T_('is not'),
@ -168,7 +169,7 @@ class Search extends playlist_object {
'description' => T_('is'), 'description' => T_('is'),
'sql' => '' 'sql' => ''
); );
$this->basetypes['boolean_subsearch'][] = array( $this->basetypes['boolean_subsearch'][] = array(
'name' => 'ne', 'name' => 'ne',
'description' => T_('is not'), 'description' => T_('is not'),
@ -181,7 +182,7 @@ class Search extends playlist_object {
'description' => T_('before'), 'description' => T_('before'),
'sql' => '<' 'sql' => '<'
); );
$this->basetypes['date'][] = array( $this->basetypes['date'][] = array(
'name' => 'gt', 'name' => 'gt',
'description' => T_('after'), 'description' => T_('after'),
@ -225,7 +226,7 @@ class Search extends playlist_object {
'widget' => array('input', 'text') 'widget' => array('input', 'text')
); );
$this->types[] = array( $this->types[] = array(
'name' => 'tag', 'name' => 'tag',
'label' => T_('Tag'), 'label' => T_('Tag'),
@ -248,7 +249,7 @@ class Search extends playlist_object {
); );
$this->types[] = array( $this->types[] = array(
'name' => 'time', 'name' => 'time',
'label' => T_('Length (in minutes)'), 'label' => T_('Length (in minutes)'),
'type' => 'numeric', 'type' => 'numeric',
'widget' => array('input', 'text') 'widget' => array('input', 'text')
@ -264,7 +265,7 @@ class Search extends playlist_object {
array( array(
'1 Star', '1 Star',
'2 Stars', '2 Stars',
'3 Stars', '3 Stars',
'4 Stars', '4 Stars',
'5 Stars' '5 Stars'
) )
@ -402,7 +403,7 @@ class Search extends playlist_object {
'type' => 'boolean_numeric', 'type' => 'boolean_numeric',
'widget' => array('select', $catalogs) 'widget' => array('select', $catalogs)
); );
$this->types[] = array( $this->types[] = array(
'name' => 'tag', 'name' => 'tag',
@ -442,7 +443,8 @@ class Search extends playlist_object {
* *
* Sanitizes raw search data * Sanitizes raw search data
*/ */
public static function clean_request($data) { public static function clean_request($data)
{
foreach ($data as $key => $value) { foreach ($data as $key => $value) {
$prefix = substr($key, 0, 4); $prefix = substr($key, 0, 4);
$value = trim($value); $value = trim($value);
@ -453,7 +455,7 @@ class Search extends playlist_object {
} }
// Figure out if they want an AND based search or an OR based search // Figure out if they want an AND based search or an OR based search
switch($data['operator']) { switch ($data['operator']) {
case 'or': case 'or':
$request['operator'] = 'OR'; $request['operator'] = 'OR';
break; break;
@ -461,9 +463,9 @@ class Search extends playlist_object {
$request['operator'] = 'AND'; $request['operator'] = 'AND';
break; break;
} }
// Verify the type // Verify the type
switch($data['type']) { switch ($data['type']) {
case 'album': case 'album':
case 'artist': case 'artist':
case 'video': case 'video':
@ -478,12 +480,13 @@ class Search extends playlist_object {
return $request; return $request;
} // end clean_request } // end clean_request
/** /**
* get_name_byid * get_name_byid
* *
* Returns the name of the saved search corresponding to the given ID * Returns the name of the saved search corresponding to the given ID
*/ */
public static function get_name_byid($id) { public static function get_name_byid($id)
{
$sql = "SELECT `name` FROM `search` WHERE `id` = '$id'"; $sql = "SELECT `name` FROM `search` WHERE `id` = '$id'";
$db_results = Dba::read($sql); $db_results = Dba::read($sql);
$r = Dba::fetch_assoc($db_results); $r = Dba::fetch_assoc($db_results);
@ -495,7 +498,8 @@ class Search extends playlist_object {
* *
* Return the IDs of all saved searches accessible by the current user. * Return the IDs of all saved searches accessible by the current user.
*/ */
public static function get_searches() { public static function get_searches()
{
$sql = "SELECT `id` from `search` WHERE `type`='public' OR " . $sql = "SELECT `id` from `search` WHERE `type`='public' OR " .
"`user`='" . $GLOBALS['user']->id . "' ORDER BY `name`"; "`user`='" . $GLOBALS['user']->id . "' ORDER BY `name`";
$db_results = Dba::read($sql); $db_results = Dba::read($sql);
@ -515,7 +519,8 @@ class Search extends playlist_object {
* This function actually runs the search and returns an array of the * This function actually runs the search and returns an array of the
* results. * results.
*/ */
public static function run($data) { public static function run($data)
{
$limit = intval($data['limit']); $limit = intval($data['limit']);
$data = Search::clean_request($data); $data = Search::clean_request($data);
@ -552,7 +557,8 @@ class Search extends playlist_object {
* *
* Does what it says on the tin. * Does what it says on the tin.
*/ */
public function delete() { public function delete()
{
$id = Dba::escape($this->id); $id = Dba::escape($this->id);
$sql = "DELETE FROM `search` WHERE `id` = ?"; $sql = "DELETE FROM `search` WHERE `id` = ?";
$db_results = Dba::write($sql, array($id)); $db_results = Dba::write($sql, array($id));
@ -564,7 +570,8 @@ class Search extends playlist_object {
* format * format
* Gussy up the data * Gussy up the data
*/ */
public function format() { public function format()
{
parent::format(); parent::format();
$this->f_link = '<a href="' . Config::get('web_path') . $this->f_link = '<a href="' . Config::get('web_path') .
'/smartplaylist.php?action=show_playlist&amp;playlist_id=' . '/smartplaylist.php?action=show_playlist&amp;playlist_id=' .
@ -577,7 +584,8 @@ class Search extends playlist_object {
* Return an array of the items output by our search (part of the * Return an array of the items output by our search (part of the
* playlist interface). * playlist interface).
*/ */
public function get_items() { public function get_items()
{
$results = array(); $results = array();
$sql = $this->to_sql(); $sql = $this->to_sql();
@ -602,7 +610,8 @@ class Search extends playlist_object {
* Returns a randomly sorted array (with an optional limit) of the items * Returns a randomly sorted array (with an optional limit) of the items
* output by our search (part of the playlist interface) * output by our search (part of the playlist interface)
*/ */
public function get_random_items($limit = null) { public function get_random_items($limit = null)
{
$results = array(); $results = array();
$sql = $this->to_sql(); $sql = $this->to_sql();
@ -624,13 +633,14 @@ class Search extends playlist_object {
return $results; return $results;
} }
/** /**
* name_to_basetype * name_to_basetype
* *
* Iterates over our array of types to find out the basetype for * Iterates over our array of types to find out the basetype for
* the passed string. * the passed string.
*/ */
public function name_to_basetype($name) { public function name_to_basetype($name)
{
foreach ($this->types as $type) { foreach ($this->types as $type) {
if ($type['name'] == $name) { if ($type['name'] == $name) {
return $type['type']; return $type['type'];
@ -639,13 +649,14 @@ class Search extends playlist_object {
return false; return false;
} }
/** /**
* parse_rules * parse_rules
* *
* Takes an array of sanitized search data from the form and generates * Takes an array of sanitized search data from the form and generates
* our real array from it. * our real array from it.
*/ */
public function parse_rules($data) { public function parse_rules($data)
{
$this->rules = array(); $this->rules = array();
foreach ($data as $rule => $value) { foreach ($data as $rule => $value) {
if (preg_match('/^rule_(\d+)$/', $rule, $ruleID)) { if (preg_match('/^rule_(\d+)$/', $rule, $ruleID)) {
@ -667,7 +678,8 @@ class Search extends playlist_object {
* *
* Save this search to the database for use as a smart playlist * Save this search to the database for use as a smart playlist
*/ */
public function save() { public function save()
{
// Make sure we have a unique name // Make sure we have a unique name
if (! $this->name) { if (! $this->name) {
$this->name = $GLOBALS['user']->username . ' - ' . date('Y-m-d H:i:s', time()); $this->name = $GLOBALS['user']->username . ' - ' . date('Y-m-d H:i:s', time());
@ -689,9 +701,10 @@ class Search extends playlist_object {
/** /**
* to_js * to_js
* *
* Outputs the javascript necessary to re-show the current set of rules. * Outputs the javascript necessary to re-show the current set of rules.
*/ */
public function to_js() { public function to_js()
{
foreach ($this->rules as $rule) { foreach ($this->rules as $rule) {
$js .= '<script type="text/javascript">' . $js .= '<script type="text/javascript">' .
'SearchRow.add("' . $rule[0] . '","' . 'SearchRow.add("' . $rule[0] . '","' .
@ -705,16 +718,18 @@ class Search extends playlist_object {
* *
* Call the appropriate real function. * Call the appropriate real function.
*/ */
public function to_sql() { public function to_sql()
{
return call_user_func(array($this, $this->searchtype . "_to_sql")); return call_user_func(array($this, $this->searchtype . "_to_sql"));
} }
/** /**
* update * update
* *
* This function updates the saved version with the current settings. * This function updates the saved version with the current settings.
*/ */
public function update() { public function update()
{
if (!$this->id) { if (!$this->id) {
return false; return false;
} }
@ -727,11 +742,12 @@ class Search extends playlist_object {
/** /**
* _mangle_data * _mangle_data
* *
* Private convenience function. Mangles the input according to a set * Private convenience function. Mangles the input according to a set
* of predefined rules so that we don't have to include this logic in * of predefined rules so that we don't have to include this logic in
* foo_to_sql. * foo_to_sql.
*/ */
private function _mangle_data($data, $type, $operator) { private function _mangle_data($data, $type, $operator)
{
if ($operator['preg_match']) { if ($operator['preg_match']) {
$data = preg_replace( $data = preg_replace(
$operator['preg_match'], $operator['preg_match'],
@ -756,7 +772,8 @@ class Search extends playlist_object {
* *
* Handles the generation of the SQL for album searches. * Handles the generation of the SQL for album searches.
*/ */
private function album_to_sql() { private function album_to_sql()
{
$sql_logic_operator = $this->logic_operator; $sql_logic_operator = $this->logic_operator;
$where = array(); $where = array();
@ -841,7 +858,8 @@ class Search extends playlist_object {
* *
* Handles the generation of the SQL for artist searches. * Handles the generation of the SQL for artist searches.
*/ */
private function artist_to_sql() { private function artist_to_sql()
{
$sql_logic_operator = $this->logic_operator; $sql_logic_operator = $this->logic_operator;
$where = array(); $where = array();
$table = array(); $table = array();
@ -903,7 +921,8 @@ class Search extends playlist_object {
* song_to_sql * song_to_sql
* Handles the generation of the SQL for song searches. * Handles the generation of the SQL for song searches.
*/ */
private function song_to_sql() { private function song_to_sql()
{
$sql_logic_operator = $this->logic_operator; $sql_logic_operator = $this->logic_operator;
$where = array(); $where = array();
@ -999,7 +1018,7 @@ class Search extends playlist_object {
break; break;
} // switch on type } // switch on type
} // foreach over rules } // foreach over rules
$where_sql = implode(" $sql_logic_operator ", $where); $where_sql = implode(" $sql_logic_operator ", $where);
// now that we know which things we want to JOIN... // now that we know which things we want to JOIN...
@ -1051,7 +1070,8 @@ class Search extends playlist_object {
* *
* Handles the generation of the SQL for video searches. * Handles the generation of the SQL for video searches.
*/ */
private function video_to_sql() { private function video_to_sql()
{
$sql_logic_operator = $this->logic_operator; $sql_logic_operator = $this->logic_operator;
$where = array(); $where = array();
@ -1085,4 +1105,3 @@ class Search extends playlist_object {
} }
} }
?>

View file

@ -25,13 +25,14 @@
* This class handles all of the session related stuff in Ampache * This class handles all of the session related stuff in Ampache
* *
*/ */
class Session { class Session
{
/** /**
* Constructor * Constructor
* This should never be called * This should never be called
*/ */
private function __construct() { private function __construct()
{
// Rien a faire // Rien a faire
} // __construct } // __construct
@ -41,7 +42,8 @@ class Session {
* This function is for opening a new session so we just verify that we * This function is for opening a new session so we just verify that we
* have a database connection, nothing more is needed. * have a database connection, nothing more is needed.
*/ */
public static function open($save_path, $session_name) { public static function open($save_path, $session_name)
{
if (!Dba::dbh()) { if (!Dba::dbh()) {
debug_event('session', 'Could not start session, no database connection', 1); debug_event('session', 'Could not start session, no database connection', 1);
return false; return false;
@ -55,7 +57,8 @@ class Session {
* *
* This is run on the end of a session, nothing to do here for now. * This is run on the end of a session, nothing to do here for now.
*/ */
public static function close() { public static function close()
{
return true; return true;
} }
@ -64,7 +67,8 @@ class Session {
* *
* This saves the session information into the database. * This saves the session information into the database.
*/ */
public static function write($key, $value) { public static function write($key, $value)
{
if (defined('NO_SESSION_UPDATE')) { if (defined('NO_SESSION_UPDATE')) {
return true; return true;
} }
@ -73,8 +77,8 @@ class Session {
// Check to see if remember me cookie is set, if so use remember // Check to see if remember me cookie is set, if so use remember
// length, otherwise use the session length // length, otherwise use the session length
$expire = isset($_COOKIE[Config::get('session_name') . '_remember']) $expire = isset($_COOKIE[Config::get('session_name') . '_remember'])
? time() + Config::get('remember_length') ? time() + Config::get('remember_length')
: time() + Config::get('session_length'); : time() + Config::get('session_length');
$sql = 'UPDATE `session` SET `value` = ?, `expire` = ? WHERE `id` = ?'; $sql = 'UPDATE `session` SET `value` = ?, `expire` = ? WHERE `id` = ?';
@ -90,8 +94,8 @@ class Session {
* *
* 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)
{
if (!strlen($key)) { return false; } if (!strlen($key)) { return false; }
// Remove anything and EVERYTHING // Remove anything and EVERYTHING
@ -111,7 +115,8 @@ class Session {
* *
* This function is randomly called and it cleans up the spoo * This function is randomly called and it cleans up the spoo
*/ */
public static function gc($maxlifetime) { public static function gc($maxlifetime)
{
$sql = 'DELETE FROM `session` WHERE `expire` < ?'; $sql = 'DELETE FROM `session` WHERE `expire` < ?';
$db_results = Dba::write($sql, array(time())); $db_results = Dba::write($sql, array(time()));
@ -128,7 +133,8 @@ class Session {
* *
* This takes a key and returns the data from the database. * This takes a key and returns the data from the database.
*/ */
public static function read($key) { public static function read($key)
{
return self::_read($key, 'value'); return self::_read($key, 'value');
} }
@ -137,14 +143,15 @@ class Session {
* *
* This returns the specified column from the session row. * This returns the specified column from the session row.
*/ */
private static function _read($key, $column) { private static function _read($key, $column)
{
$sql = 'SELECT * FROM `session` WHERE `id` = ? AND `expire` > ?'; $sql = 'SELECT * FROM `session` WHERE `id` = ? AND `expire` > ?';
$db_results = Dba::read($sql, array($key, time())); $db_results = Dba::read($sql, array($key, time()));
if ($results = Dba::fetch_assoc($db_results)) { if ($results = Dba::fetch_assoc($db_results)) {
return $results[$column]; return $results[$column];
} }
debug_event('session', 'Unable to read session from key ' . $key . ' no data found', 5); debug_event('session', 'Unable to read session from key ' . $key . ' no data found', 5);
return ''; return '';
@ -155,7 +162,8 @@ class Session {
* *
* This returns the username associated with a session ID, if any * This returns the username associated with a session ID, if any
*/ */
public static function username($key) { public static function username($key)
{
return self::_read($key, 'username'); return self::_read($key, 'username');
} }
@ -165,13 +173,13 @@ class Session {
* it takes care of setting the initial cookie, and inserting the first * it takes care of setting the initial cookie, and inserting the first
* chunk of data, nifty ain't it! * chunk of data, nifty ain't it!
*/ */
public static function create($data) { public static function create($data)
{
// Regenerate the session ID to prevent fixation // Regenerate the session ID to prevent fixation
switch ($data['type']) { switch ($data['type']) {
case 'api': case 'api':
case 'stream': case 'stream':
$key = isset($data['sid']) $key = isset($data['sid'])
? $data['sid'] ? $data['sid']
: md5(uniqid(rand(), true)); : md5(uniqid(rand(), true));
break; break;
@ -193,8 +201,7 @@ class Session {
if ($type == 'stream') { if ($type == 'stream') {
$expire = time() + Config::get('stream_length'); $expire = time() + Config::get('stream_length');
} } else {
else {
$expire = time() + Config::get('session_length'); $expire = time() + Config::get('session_length');
} }
@ -221,8 +228,8 @@ class Session {
* This checks for an existing session. If it's still valid we go ahead * This checks for an existing session. If it's still valid we go ahead
* and start it and return true. * and start it and return true.
*/ */
public static function check() { public static function check()
{
$session_name = Config::get('session_name'); $session_name = Config::get('session_name');
// No cookie no go! // No cookie no go!
@ -258,7 +265,8 @@ class Session {
* exists, it also provides an array of keyed data that may be required * exists, it also provides an array of keyed data that may be required
* based on the type. * based on the type.
*/ */
public static function exists($type, $key, $data=array()) { public static function exists($type, $key, $data=array())
{
// Switch on the type they pass // Switch on the type they pass
switch ($type) { switch ($type) {
case 'api': case 'api':
@ -299,10 +307,11 @@ class Session {
* *
* This takes a SID and extends its expiration. * This takes a SID and extends its expiration.
*/ */
public static function extend($sid, $type = null) { public static function extend($sid, $type = null)
{
$time = time(); $time = time();
$expire = isset($_COOKIE[Config::get('session_name') . '_remember']) $expire = isset($_COOKIE[Config::get('session_name') . '_remember'])
? $time + Config::get('remember_length') ? $time + Config::get('remember_length')
: $time + Config::get('session_length'); : $time + Config::get('session_length');
if ($type == 'stream') { if ($type == 'stream') {
@ -323,7 +332,8 @@ class Session {
* This function is called when the object is included, this sets up the * This function is called when the object is included, this sets up the
* session_save_handler * 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;
@ -350,7 +360,8 @@ class Session {
* a cookie at the same time as a header redirect. As such on view of a * a cookie at the same time as a header redirect. As such on view of a
* login a cookie is set with the proper name. * login a cookie is set with the proper name.
*/ */
public static function create_cookie() { public static function create_cookie()
{
// Set up the cookie prefs before we throw down, this is very important // Set up 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');
@ -371,12 +382,13 @@ class Session {
* *
* 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, true); Config::set('cookie_life', $remember_length, true);
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, '/');
} }
/** /**
@ -385,7 +397,8 @@ class Session {
* This function sets the cache limiting to public if you are running * This function sets the cache limiting to public if you are running
* some flavor of IE and not using HTTPS. * some flavor of IE and not using HTTPS.
*/ */
public static function ungimp_ie() { public static function ungimp_ie()
{
// If no https, no ungimpage required // If no https, no ungimpage required
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'on') { if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'on') {
return true; return true;
@ -399,5 +412,4 @@ class Session {
return true; return true;
} }
} }
?>

View file

@ -20,8 +20,8 @@
* *
*/ */
class Shoutbox { class Shoutbox
{
public $id; public $id;
/** /**
@ -29,8 +29,8 @@ class Shoutbox {
* This pulls the shoutbox information from the database and returns * This pulls the shoutbox information from the database and returns
* a constructed object, uses user_shout table * a constructed object, uses user_shout table
*/ */
public function __construct($shout_id) { public function __construct($shout_id)
{
// Load the data from the database // Load the data from the database
$this->_get_info($shout_id); $this->_get_info($shout_id);
@ -42,8 +42,8 @@ class Shoutbox {
* _get_info * _get_info
* does the db call, reads from the user_shout table * does the db call, reads from the user_shout table
*/ */
private function _get_info($shout_id) { private function _get_info($shout_id)
{
$sticky_id = Dba::escape($shout_id); $sticky_id = Dba::escape($shout_id);
$sql = "SELECT * FROM `user_shout` WHERE `id`='$shout_id'"; $sql = "SELECT * FROM `user_shout` WHERE `id`='$shout_id'";
@ -64,8 +64,9 @@ class Shoutbox {
* *
* Cleans out orphaned shoutbox items * Cleans out orphaned shoutbox items
*/ */
public static function gc() { public static function gc()
foreach(array('song', 'album', 'artist') as $object_type) { {
foreach (array('song', 'album', 'artist') as $object_type) {
Dba::write("DELETE FROM `user_shout` USING `user_shout` LEFT JOIN `$object_type` ON `$object_type`.`id` = `user_shout`.`object_id` WHERE `$object_type`.`id` IS NULL AND `user_shout`.`object_type` = '$object_type'"); Dba::write("DELETE FROM `user_shout` USING `user_shout` LEFT JOIN `$object_type` ON `$object_type`.`id` = `user_shout`.`object_id` WHERE `$object_type`.`id` IS NULL AND `user_shout`.`object_type` = '$object_type'");
} }
} }
@ -75,8 +76,8 @@ class Shoutbox {
* This returns the top user_shouts, shoutbox objects are always shown regardless and count against the total * This returns the top user_shouts, shoutbox objects are always shown regardless and count against the total
* number of objects shown * number of objects shown
*/ */
public static function get_top($limit) { public static function get_top($limit)
{
$shouts = self::get_sticky(); $shouts = self::get_sticky();
// If we've already got too many stop here // If we've already got too many stop here
@ -102,8 +103,8 @@ class Shoutbox {
* get_sticky * get_sticky
* This returns all current sticky shoutbox items * This returns all current sticky shoutbox items
*/ */
public static function get_sticky() { public static function get_sticky()
{
$sql = "SELECT * FROM `user_shout` WHERE `sticky`='1' ORDER BY `date` DESC"; $sql = "SELECT * FROM `user_shout` WHERE `sticky`='1' ORDER BY `date` DESC";
$db_results = Dba::read($sql); $db_results = Dba::read($sql);
@ -121,8 +122,8 @@ class Shoutbox {
* get_object * get_object
* This takes a type and an ID and returns a created object * This takes a type and an ID and returns a created object
*/ */
public static function get_object($type,$object_id) { public static function get_object($type,$object_id)
{
$allowed_objects = array('song','genre','album','artist','radio'); $allowed_objects = array('song','genre','album','artist','radio');
if (!in_array($type,$allowed_objects)) { if (!in_array($type,$allowed_objects)) {
@ -140,8 +141,8 @@ class Shoutbox {
* This returns an image tag if the type of object we're currently rolling with * This returns an image tag if the type of object we're currently rolling with
* has an image associated with it * has an image associated with it
*/ */
public function get_image() { public function get_image()
{
switch ($this->object_type) { switch ($this->object_type) {
case 'album': case 'album':
$image_string = "<img class=\"shoutboximage\" height=\"75\" width=\"75\" src=\"" . Config::get('web_path') . "/image.php?id=" . $this->object_id . "&amp;thumb=1\" />"; $image_string = "<img class=\"shoutboximage\" height=\"75\" width=\"75\" src=\"" . Config::get('web_path') . "/image.php?id=" . $this->object_id . "&amp;thumb=1\" />";
@ -166,8 +167,8 @@ class Shoutbox {
* create * create
* This takes a key'd array of data as input and inserts a new shoutbox entry, it returns the auto_inc id * This takes a key'd array of data as input and inserts a new shoutbox entry, it returns the auto_inc id
*/ */
public static function create($data) { public static function create($data)
{
$user = Dba::escape($GLOBALS['user']->id); $user = Dba::escape($GLOBALS['user']->id);
$text = Dba::escape(strip_tags($data['comment'])); $text = Dba::escape(strip_tags($data['comment']));
$date = time(); $date = time();
@ -189,8 +190,8 @@ class Shoutbox {
* update * update
* This takes a key'd array of data as input and updates a shoutbox entry * This takes a key'd array of data as input and updates a shoutbox entry
*/ */
public static function update($data) { public static function update($data)
{
$id = Dba::escape($data['shout_id']); $id = Dba::escape($data['shout_id']);
$text = Dba::escape(strip_tags($data['comment'])); $text = Dba::escape(strip_tags($data['comment']));
$sticky = make_bool($data['sticky']); $sticky = make_bool($data['sticky']);
@ -207,7 +208,8 @@ class Shoutbox {
* this function takes the object and reformats some values * this function takes the object and reformats some values
*/ */
public function format() { public function format()
{
$this->sticky = ($this->sticky == "0") ? 'No' : 'Yes'; $this->sticky = ($this->sticky == "0") ? 'No' : 'Yes';
$this->date = date("m\/d\/Y - H:i", $this->date); $this->date = date("m\/d\/Y - H:i", $this->date);
return true; return true;
@ -219,8 +221,8 @@ class Shoutbox {
* this function deletes a specific shoutbox entry * this function deletes a specific shoutbox entry
*/ */
public function delete($shout_id) { public function delete($shout_id)
{
// Delete the shoutbox post // Delete the shoutbox post
$shout_id = Dba::escape($shout_id); $shout_id = Dba::escape($shout_id);
$sql = "DELETE FROM `user_shout` WHERE `id`='$shout_id'"; $sql = "DELETE FROM `user_shout` WHERE `id`='$shout_id'";
@ -229,4 +231,3 @@ class Shoutbox {
} // delete } // delete
} // Shoutbox class } // Shoutbox class
?>

View file

@ -20,8 +20,8 @@
* *
*/ */
class Song extends database_object implements media { class Song extends database_object implements media
{
/* Variables from DB */ /* Variables from DB */
public $id; public $id;
public $file; public $file;
@ -53,8 +53,8 @@ class Song extends database_object implements media {
* *
* Song class, for modifing a song. * Song class, for modifing a song.
*/ */
public function __construct($id = null) { public function __construct($id = null)
{
if (!$id) { return false; } if (!$id) { return false; }
$this->id = intval($id); $this->id = intval($id);
@ -66,8 +66,7 @@ class Song extends database_object implements media {
$data = pathinfo($this->file); $data = pathinfo($this->file);
$this->type = strtolower($data['extension']); $this->type = strtolower($data['extension']);
$this->mime = self::type_to_mime($this->type); $this->mime = self::type_to_mime($this->type);
} } else {
else {
$this->id = null; $this->id = null;
return false; return false;
} }
@ -81,7 +80,8 @@ class Song extends database_object implements media {
* *
* This inserts the song described by the passed array * This inserts the song described by the passed array
*/ */
public static function insert($results) { public static function insert($results)
{
$catalog = $results['catalog']; $catalog = $results['catalog'];
$file = $results['file']; $file = $results['file'];
$title = trim($results['title']) ?: $file; $title = trim($results['title']) ?: $file;
@ -146,7 +146,8 @@ class Song extends database_object implements media {
* *
* Cleans up the song_data table * Cleans up the song_data table
*/ */
public static function gc() { public static function gc()
{
Dba::write('DELETE FROM `song_data` USING `song_data` LEFT JOIN `song` ON `song`.`id` = `song_data`.`song_id` WHERE `song`.`id` IS NULL'); Dba::write('DELETE FROM `song_data` USING `song_data` LEFT JOIN `song` ON `song`.`id` = `song_data`.`song_id` WHERE `song`.`id` IS NULL');
} }
@ -157,8 +158,8 @@ class Song extends database_object implements media {
* browse all at once and storing it in the cache, this can help if the * browse all at once and storing it in the cache, this can help if the
* db connection is the slow point. * db connection is the slow point.
*/ */
public static function build_cache($song_ids) { public static function build_cache($song_ids)
{
if (!is_array($song_ids) || !count($song_ids)) { return false; } if (!is_array($song_ids) || !count($song_ids)) { return false; }
$idlist = '(' . implode(',', $song_ids) . ')'; $idlist = '(' . implode(',', $song_ids) . ')';
@ -219,8 +220,8 @@ class Song extends database_object implements media {
/** /**
* _get_info * _get_info
*/ */
private function _get_info() { private function _get_info()
{
$id = $this->id; $id = $this->id;
if (parent::is_cached('song', $id)) { if (parent::is_cached('song', $id)) {
@ -238,19 +239,19 @@ class Song extends database_object implements media {
if (Config::get('show_played_times')) { if (Config::get('show_played_times')) {
$results['object_cnt'] = Stats::get_object_count('song', $results['id']); $results['object_cnt'] = Stats::get_object_count('song', $results['id']);
} }
$sql = 'SELECT `mbid` FROM `album` WHERE `id` = ?'; $sql = 'SELECT `mbid` FROM `album` WHERE `id` = ?';
$db_results = Dba::read($sql, array($results['album'])); $db_results = Dba::read($sql, array($results['album']));
if ($album_res = Dba::fetch_assoc($db_results)) { if ($album_res = Dba::fetch_assoc($db_results)) {
$results['album_mbid'] = $album_res['mbid']; $results['album_mbid'] = $album_res['mbid'];
} }
$sql = 'SELECT `mbid` FROM `artist` WHERE `id` = ?'; $sql = 'SELECT `mbid` FROM `artist` WHERE `id` = ?';
$db_results = Dba::read($sql, array($results['artist'])); $db_results = Dba::read($sql, array($results['artist']));
if ($artist_res = Dba::fetch_assoc($db_results)) { if ($artist_res = Dba::fetch_assoc($db_results)) {
$results['artist_mbid'] = $artist_res['mbid']; $results['artist_mbid'] = $artist_res['mbid'];
} }
parent::add_to_cache('song', $id, $results); parent::add_to_cache('song', $id, $results);
return $results; return $results;
} }
@ -263,8 +264,8 @@ class Song extends database_object implements media {
* This function gathers information from the song_ext_info table and adds it to the * This function gathers information from the song_ext_info table and adds it to the
* current object * current object
*/ */
public function _get_ext_info() { public function _get_ext_info()
{
$id = intval($this->id); $id = intval($this->id);
if (parent::is_cached('song_data',$id)) { if (parent::is_cached('song_data',$id)) {
@ -286,8 +287,8 @@ class Song extends database_object implements media {
* fill_ext_info * fill_ext_info
* This calls the _get_ext_info and then sets the correct vars * This calls the _get_ext_info and then sets the correct vars
*/ */
public function fill_ext_info() { public function fill_ext_info()
{
$info = $this->_get_ext_info(); $info = $this->_get_ext_info();
foreach ($info as $key=>$value) { foreach ($info as $key=>$value) {
@ -303,7 +304,8 @@ class Song extends database_object implements media {
* *
* Returns the mime type for the specified file extension/type * Returns the mime type for the specified file extension/type
*/ */
public static function type_to_mime($type) { public static function type_to_mime($type)
{
// FIXME: This should really be done the other way around. // FIXME: This should really be done the other way around.
// Store the mime type in the database, and provide a function // Store the mime type in the database, and provide a function
// to make it a human-friendly type. // to make it a human-friendly type.
@ -355,8 +357,8 @@ class Song extends database_object implements media {
* *
* Gets a list of the disabled songs for and returns an array of Songs * Gets a list of the disabled songs for and returns an array of Songs
*/ */
public static function get_disabled($count = 0) { public static function get_disabled($count = 0)
{
$results = array(); $results = array();
$sql = "SELECT `id` FROM `song` WHERE `enabled`='0'"; $sql = "SELECT `id` FROM `song` WHERE `enabled`='0'";
@ -377,13 +379,14 @@ class Song extends database_object implements media {
* This function takes a search type and returns a list of probable * This function takes a search type and returns a list of probable
* duplicates * duplicates
*/ */
public static function find_duplicates($search_type) { public static function find_duplicates($search_type)
{
$where_sql = $_REQUEST['search_disabled'] ? '' : "WHERE `enabled` != '0'"; $where_sql = $_REQUEST['search_disabled'] ? '' : "WHERE `enabled` != '0'";
$sql = 'SELECT `id`, `artist`, `album`, `title`, ' . $sql = 'SELECT `id`, `artist`, `album`, `title`, ' .
'COUNT(`title`) FROM `song` ' . $where_sql . 'COUNT(`title`) FROM `song` ' . $where_sql .
' GROUP BY `title`'; ' GROUP BY `title`';
if ($search_type == 'artist_title' || if ($search_type == 'artist_title' ||
$search_type == 'artist_album_title') { $search_type == 'artist_album_title') {
$sql .= ',`artist`'; $sql .= ',`artist`';
} }
@ -404,16 +407,17 @@ class Song extends database_object implements media {
return $results; return $results;
} }
public static function get_duplicate_info($dupe, $search_type) { public static function get_duplicate_info($dupe, $search_type)
{
$sql = 'SELECT `id` FROM `song` ' . $sql = 'SELECT `id` FROM `song` ' .
"WHERE `title`='" . Dba::escape($item['title']) . "' "; "WHERE `title`='" . Dba::escape($item['title']) . "' ";
if ($search_type == 'artist_title' || if ($search_type == 'artist_title' ||
$search_type == 'artist_album_title') { $search_type == 'artist_album_title') {
$sql .= "AND `artist`='" . Dba::escape($item['artist']) . "' "; $sql .= "AND `artist`='" . Dba::escape($item['artist']) . "' ";
} }
if ($search_type == 'artist_album_title') { if ($search_type == 'artist_album_title') {
$sql .= "AND `album` = '" . Dba::escape($item['album']) . "' "; $sql .= "AND `album` = '" . Dba::escape($item['album']) . "' ";
} }
$sql .= 'ORDER BY `time`,`bitrate`,`size`'; $sql .= 'ORDER BY `time`,`bitrate`,`size`';
@ -432,7 +436,8 @@ class Song extends database_object implements media {
* get_album_name * get_album_name
* gets the name of $this->album, allows passing of id * gets the name of $this->album, allows passing of id
*/ */
public function get_album_name($album_id=0) { public function get_album_name($album_id=0)
{
if (!$album_id) { $album_id = $this->album; } if (!$album_id) { $album_id = $this->album; }
$album = new Album($album_id); $album = new Album($album_id);
if ($album->prefix) if ($album->prefix)
@ -445,8 +450,8 @@ class Song extends database_object implements media {
* get_artist_name * get_artist_name
* gets the name of $this->artist, allows passing of id * gets the name of $this->artist, allows passing of id
*/ */
public function get_artist_name($artist_id=0) { public function get_artist_name($artist_id=0)
{
if (!$artist_id) { $artist_id = $this->artist; } if (!$artist_id) { $artist_id = $this->artist; }
$artist = new Artist($artist_id); $artist = new Artist($artist_id);
if ($artist->prefix) if ($artist->prefix)
@ -461,8 +466,8 @@ class Song extends database_object implements media {
* This just returns true or false depending on if this song is flagged for something * This just returns true or false depending on if this song is flagged for something
* We don't care what so we limit the SELECT to 1 * We don't care what so we limit the SELECT to 1
*/ */
public function has_flag() { public function has_flag()
{
$sql = "SELECT `id` FROM `flagged` WHERE `object_type`='song' AND `object_id`='$this->id' LIMIT 1"; $sql = "SELECT `id` FROM `flagged` WHERE `object_type`='song' AND `object_id`='$this->id' LIMIT 1";
$db_results = Dba::read($sql); $db_results = Dba::read($sql);
@ -479,8 +484,8 @@ class Song extends database_object implements media {
* this checks to see if the current object has been played * this checks to see if the current object has been played
* if not then it sets it to played * if not then it sets it to played
*/ */
public function set_played() { public function set_played()
{
if ($this->played) { if ($this->played) {
return true; return true;
} }
@ -499,8 +504,8 @@ class Song extends database_object implements media {
* it returns false if nothing has changes, or the true * it returns false if nothing has changes, or the true
* if they have. Static because it doesn't need this * if they have. Static because it doesn't need this
*/ */
public static function compare_song_information($song,$new_song) { public static function compare_song_information($song,$new_song)
{
// Remove some stuff we don't care about // Remove some stuff we don't care about
unset($song->catalog,$song->played,$song->enabled,$song->addition_time,$song->update_time,$song->type); unset($song->catalog,$song->played,$song->enabled,$song->addition_time,$song->update_time,$song->type);
@ -544,8 +549,8 @@ class Song extends database_object implements media {
* do and then calls the helper functions as needed. This will also * do and then calls the helper functions as needed. This will also
* cause the song to be flagged * cause the song to be flagged
*/ */
public function update($data) { public function update($data)
{
foreach ($data as $key=>$value) { foreach ($data as $key=>$value) {
switch ($key) { switch ($key) {
case 'artist': case 'artist':
@ -589,8 +594,8 @@ class Song extends database_object implements media {
* each little part of the song... lastly it updates * each little part of the song... lastly it updates
* the "update_time" of the song * the "update_time" of the song
*/ */
public static function update_song($song_id, $new_song) { public static function update_song($song_id, $new_song)
{
$title = Dba::escape($new_song->title); $title = Dba::escape($new_song->title);
$bitrate = Dba::escape($new_song->bitrate); $bitrate = Dba::escape($new_song->bitrate);
$rate = Dba::escape($new_song->rate); $rate = Dba::escape($new_song->rate);
@ -628,8 +633,8 @@ class Song extends database_object implements media {
* update_year * update_year
* update the year tag * update the year tag
*/ */
public static function update_year($new_year,$song_id) { public static function update_year($new_year,$song_id)
{
self::_update_item('year',$new_year,$song_id,'50'); self::_update_item('year',$new_year,$song_id,'50');
} // update_year } // update_year
@ -638,8 +643,8 @@ class Song extends database_object implements media {
* update_language * update_language
* This updates the language tag of the song * This updates the language tag of the song
*/ */
public static function update_language($new_lang,$song_id) { public static function update_language($new_lang,$song_id)
{
self::_update_ext_item('language',$new_lang,$song_id,'50'); self::_update_ext_item('language',$new_lang,$song_id,'50');
} // update_language } // update_language
@ -648,8 +653,8 @@ class Song extends database_object implements media {
* update_comment * update_comment
* updates the comment field * updates the comment field
*/ */
public static function update_comment($new_comment,$song_id) { public static function update_comment($new_comment,$song_id)
{
self::_update_ext_item('comment',$new_comment,$song_id,'50'); self::_update_ext_item('comment',$new_comment,$song_id,'50');
} // update_comment } // update_comment
@ -658,8 +663,8 @@ class Song extends database_object implements media {
* update_lyrics * update_lyrics
* updates the lyrics field * updates the lyrics field
*/ */
public static function update_lyrics($new_lyrics,$song_id) { public static function update_lyrics($new_lyrics,$song_id)
{
self::_update_ext_item('lyrics',$new_lyrics,$song_id,'50'); self::_update_ext_item('lyrics',$new_lyrics,$song_id,'50');
} // update_lyrics } // update_lyrics
@ -668,8 +673,8 @@ class Song extends database_object implements media {
* update_title * update_title
* updates the title field * updates the title field
*/ */
public static function update_title($new_title,$song_id) { public static function update_title($new_title,$song_id)
{
self::_update_item('title',$new_title,$song_id,'50'); self::_update_item('title',$new_title,$song_id,'50');
} // update_title } // update_title
@ -678,8 +683,8 @@ class Song extends database_object implements media {
* update_bitrate * update_bitrate
* updates the bitrate field * updates the bitrate field
*/ */
public static function update_bitrate($new_bitrate,$song_id) { public static function update_bitrate($new_bitrate,$song_id)
{
self::_update_item('bitrate',$new_bitrate,$song_id,'50'); self::_update_item('bitrate',$new_bitrate,$song_id,'50');
} // update_bitrate } // update_bitrate
@ -688,8 +693,8 @@ class Song extends database_object implements media {
* update_rate * update_rate
* updates the rate field * updates the rate field
*/ */
public static function update_rate($new_rate,$song_id) { public static function update_rate($new_rate,$song_id)
{
self::_update_item('rate',$new_rate,$song_id,'50'); self::_update_item('rate',$new_rate,$song_id,'50');
} // update_rate } // update_rate
@ -698,8 +703,8 @@ class Song extends database_object implements media {
* update_mode * update_mode
* updates the mode field * updates the mode field
*/ */
public static function update_mode($new_mode,$song_id) { public static function update_mode($new_mode,$song_id)
{
self::_update_item('mode',$new_mode,$song_id,'50'); self::_update_item('mode',$new_mode,$song_id,'50');
} // update_mode } // update_mode
@ -708,8 +713,8 @@ class Song extends database_object implements media {
* update_size * update_size
* updates the size field * updates the size field
*/ */
public static function update_size($new_size,$song_id) { public static function update_size($new_size,$song_id)
{
self::_update_item('size',$new_size,$song_id,'50'); self::_update_item('size',$new_size,$song_id,'50');
} // update_size } // update_size
@ -718,8 +723,8 @@ class Song extends database_object implements media {
* update_time * update_time
* updates the time field * updates the time field
*/ */
public static function update_time($new_time,$song_id) { public static function update_time($new_time,$song_id)
{
self::_update_item('time',$new_time,$song_id,'50'); self::_update_item('time',$new_time,$song_id,'50');
} // update_time } // update_time
@ -728,14 +733,14 @@ class Song extends database_object implements media {
* update_track * update_track
* this updates the track field * this updates the track field
*/ */
public static function update_track($new_track,$song_id) { public static function update_track($new_track,$song_id)
{
self::_update_item('track',$new_track,$song_id,'50'); self::_update_item('track',$new_track,$song_id,'50');
} // update_track } // update_track
public static function update_mbid($new_mbid,$song_id) { public static function update_mbid($new_mbid,$song_id)
{
self::_update_item('mbid',$new_mbid,$song_id,'50'); self::_update_item('mbid',$new_mbid,$song_id,'50');
} // update_mbid } // update_mbid
@ -744,8 +749,8 @@ class Song extends database_object implements media {
* update_artist * update_artist
* updates the artist field * updates the artist field
*/ */
public static function update_artist($new_artist,$song_id) { public static function update_artist($new_artist,$song_id)
{
self::_update_item('artist',$new_artist,$song_id,'50'); self::_update_item('artist',$new_artist,$song_id,'50');
} // update_artist } // update_artist
@ -754,8 +759,8 @@ class Song extends database_object implements media {
* update_album * update_album
* updates the album field * updates the album field
*/ */
public static function update_album($new_album,$song_id) { public static function update_album($new_album,$song_id)
{
self::_update_item('album',$new_album,$song_id,'50'); self::_update_item('album',$new_album,$song_id,'50');
} // update_album } // update_album
@ -764,8 +769,8 @@ class Song extends database_object implements media {
* update_utime * update_utime
* sets a new update time * sets a new update time
*/ */
public static function update_utime($song_id,$time=0) { public static function update_utime($song_id,$time=0)
{
if (!$time) { $time = time(); } if (!$time) { $time = time(); }
self::_update_item('update_time',$time,$song_id,'75'); self::_update_item('update_time',$time,$song_id,'75');
@ -776,8 +781,8 @@ class Song extends database_object implements media {
* update_played * update_played
* sets the played flag * sets the played flag
*/ */
public static function update_played($new_played,$song_id) { public static function update_played($new_played,$song_id)
{
self::_update_item('played',$new_played,$song_id,'25'); self::_update_item('played',$new_played,$song_id,'25');
} // update_played } // update_played
@ -786,8 +791,8 @@ class Song extends database_object implements media {
* update_enabled * update_enabled
* sets the enabled flag * sets the enabled flag
*/ */
public static function update_enabled($new_enabled,$song_id) { public static function update_enabled($new_enabled,$song_id)
{
self::_update_item('enabled',$new_enabled,$song_id,'75'); self::_update_item('enabled',$new_enabled,$song_id,'75');
} // update_enabled } // update_enabled
@ -799,8 +804,8 @@ class Song extends database_object implements media {
* against $GLOBALS['user'] to make sure they are allowed to update this record * against $GLOBALS['user'] to make sure they are allowed to update this record
* it then updates it and sets $this->{$field} to the new value * it then updates it and sets $this->{$field} to the new value
*/ */
private static function _update_item($field,$value,$song_id,$level) { private static function _update_item($field,$value,$song_id,$level)
{
/* Check them Rights! */ /* Check them Rights! */
if (!Access::check('interface',$level)) { return false; } if (!Access::check('interface',$level)) { return false; }
@ -821,8 +826,8 @@ class Song extends database_object implements media {
* This updates a song record that is housed in the song_ext_info table * This updates a song record that is housed in the song_ext_info table
* These are items that aren't used normally, and often large/informational only * These are items that aren't used normally, and often large/informational only
*/ */
private static function _update_ext_item($field,$value,$song_id,$level) { private static function _update_ext_item($field,$value,$song_id,$level)
{
/* Check them rights boy! */ /* Check them rights boy! */
if (!Access::check('interface',$level)) { return false; } if (!Access::check('interface',$level)) { return false; }
@ -841,8 +846,8 @@ class Song extends database_object implements media {
* and does a ton of formating on it creating f_??? variables on the current * and does a ton of formating on it creating f_??? variables on the current
* object * object
*/ */
public function format() { public function format()
{
$this->fill_ext_info(); $this->fill_ext_info();
// Format the filename // Format the filename
@ -896,8 +901,8 @@ class Song extends database_object implements media {
* This reformats the song information based on the catalog * This reformats the song information based on the catalog
* rename patterns * rename patterns
*/ */
public function format_pattern() { public function format_pattern()
{
$extension = ltrim(substr($this->file,strlen($this->file)-4,4),"."); $extension = ltrim(substr($this->file,strlen($this->file)-4,4),".");
$catalog = Catalog::create_from_id($this->catalog); $catalog = Catalog::create_from_id($this->catalog);
@ -934,8 +939,8 @@ class Song extends database_object implements media {
* This returns all of the 'data' fields for this object, we need to filter out some that we don't * This returns all of the 'data' fields for this object, we need to filter out some that we don't
* want to present to a user, and add some that don't exist directly on the object but are related * want to present to a user, and add some that don't exist directly on the object but are related
*/ */
public static function get_fields() { public static function get_fields()
{
$fields = get_class_vars('Song'); $fields = get_class_vars('Song');
unset($fields['id'],$fields['_transcoded'],$fields['_fake'],$fields['cache_hit'],$fields['mime'],$fields['type']); unset($fields['id'],$fields['_transcoded'],$fields['_fake'],$fields['cache_hit'],$fields['mime'],$fields['type']);
@ -955,8 +960,8 @@ class Song extends database_object implements media {
* get_from_path * get_from_path
* This returns all of the songs that exist under the specified path * This returns all of the songs that exist under the specified path
*/ */
public static function get_from_path($path) { public static function get_from_path($path)
{
$path = Dba::escape($path); $path = Dba::escape($path);
$sql = "SELECT * FROM `song` WHERE `file` LIKE '$path%'"; $sql = "SELECT * FROM `song` WHERE `file` LIKE '$path%'";
@ -977,8 +982,8 @@ class Song extends database_object implements media {
* @discussion returns the path of the song file stripped of the catalog path * @discussion returns the path of the song file stripped of the catalog path
* used for mpd playback * used for mpd playback
*/ */
public function get_rel_path($file_path=0,$catalog_id=0) { public function get_rel_path($file_path=0,$catalog_id=0)
{
if (!$file_path) { if (!$file_path) {
$info = $this->_get_info(); $info = $this->_get_info();
$file_path = $info->file; $file_path = $info->file;
@ -997,8 +1002,8 @@ class Song extends database_object implements media {
* a stream URL taking into account the downsmapling mojo and everything * a stream URL taking into account the downsmapling mojo and everything
* else, this is the true function * else, this is the true function
*/ */
public static function play_url($oid) { public static function play_url($oid)
{
$song = new Song($oid); $song = new Song($oid);
$user_id = $GLOBALS['user']->id ? scrub_out($GLOBALS['user']->id) : '-1'; $user_id = $GLOBALS['user']->id ? scrub_out($GLOBALS['user']->id) : '-1';
$type = $song->type; $type = $song->type;
@ -1022,8 +1027,8 @@ class Song extends database_object implements media {
* it uses the popular threshold to figure out how many to pull * it uses the popular threshold to figure out how many to pull
* it will only return unique object * it will only return unique object
*/ */
public static function get_recently_played($user_id='') { public static function get_recently_played($user_id='')
{
$user_id = Dba::escape($user_id); $user_id = Dba::escape($user_id);
$sql = "SELECT `object_id`, `user`, `object_type`, `date` " . $sql = "SELECT `object_id`, `user`, `object_type`, `date` " .
@ -1046,11 +1051,13 @@ class Song extends database_object implements media {
} // get_recently_played } // get_recently_played
public function get_stream_types() { public function get_stream_types()
{
return Song::get_stream_types_for_type($this->type); return Song::get_stream_types_for_type($this->type);
} // end stream_types } // end stream_types
public static function get_stream_types_for_type($type) { public static function get_stream_types_for_type($type)
{
$types = array(); $types = array();
$transcode = Config::get('transcode_' . $type); $transcode = Config::get('transcode_' . $type);
@ -1062,21 +1069,19 @@ class Song extends database_object implements media {
} }
return $types; return $types;
} // end stream_types } // end stream_types
public function get_transcode_settings($target = null) { public function get_transcode_settings($target = null)
{
$source = $this->type; $source = $this->type;
if ($target) { if ($target) {
debug_event('transcode', 'Explicit format request', 5); debug_event('transcode', 'Explicit format request', 5);
} } else if ($target = Config::get('encode_target_' . $source)) {
else if ($target = Config::get('encode_target_' . $source)) {
debug_event('transcode', 'Defaulting to configured target format for ' . $source, 5); debug_event('transcode', 'Defaulting to configured target format for ' . $source, 5);
} } else if ($target = Config::get('encode_target')) {
else if ($target = Config::get('encode_target')) {
debug_event('transcode', 'Using default target format', 5); debug_event('transcode', 'Using default target format', 5);
} } else {
else {
$target = $source; $target = $source;
debug_event('transcode', 'No default target for ' . $source . ', choosing to resample', 5); debug_event('transcode', 'No default target for ' . $source . ', choosing to resample', 5);
} }
@ -1097,4 +1102,3 @@ class Song extends database_object implements media {
} }
} // end of song class } // end of song class
?>

View file

@ -28,22 +28,22 @@
* but that's not good, all done through here. * but that's not good, all done through here.
* *
*/ */
class Stats { class Stats
{
/* Base vars */ /* Base vars */
var $id; public $id;
var $object_type; public $object_type;
var $object_id; public $object_id;
var $date; public $date;
var $user; public $user;
/** /**
* Constructor * Constructor
* This doesn't do anything currently * This doesn't do anything currently
*/ */
public function __construct() { public function __construct()
{
return true; return true;
} // Constructor } // Constructor
@ -53,7 +53,8 @@ class Stats {
* *
* This clears all stats for _everything_. * This clears all stats for _everything_.
*/ */
public static function clear() { public static function clear()
{
Dba::write('TRUNCATE `object_count`'); Dba::write('TRUNCATE `object_count`');
Dba::write('UPDATE `song` SET `played` = 0'); Dba::write('UPDATE `song` SET `played` = 0');
} }
@ -63,8 +64,9 @@ class Stats {
* *
* This removes stats for things that no longer exist. * This removes stats for things that no longer exist.
*/ */
public static function gc() { public static function gc()
foreach(array('song', 'album', 'artist', 'live_stream', 'video') as $object_type) { {
foreach (array('song', 'album', 'artist', 'live_stream', 'video') as $object_type) {
Dba::write("DELETE FROM `object_count` USING `object_count` LEFT JOIN `$object_type` ON `$object_type`.`id` = `object_count`.`object_id` WHERE `object_type` = '$object_type' AND `$object_type`.`id` IS NULL"); Dba::write("DELETE FROM `object_count` USING `object_count` LEFT JOIN `$object_type` ON `$object_type`.`id` = `object_count`.`object_id` WHERE `object_type` = '$object_type' AND `$object_type`.`id` IS NULL");
} }
} }
@ -74,8 +76,8 @@ class Stats {
* This inserts a new record for the specified object * This inserts a new record for the specified object
* with the specified information, amazing! * with the specified information, amazing!
*/ */
public static function insert($type,$oid,$user) { public static function insert($type,$oid,$user)
{
$type = self::validate_type($type); $type = self::validate_type($type);
$sql = "INSERT INTO `object_count` (`object_type`,`object_id`,`date`,`user`) " . $sql = "INSERT INTO `object_count` (`object_type`,`object_id`,`date`,`user`) " .
@ -87,18 +89,18 @@ class Stats {
} }
} // insert } // insert
/** /**
* get_object_count * get_object_count
* Get count for an object * Get count for an object
*/ */
public static function get_object_count($object_type, $object_id) { public static function get_object_count($object_type, $object_id)
{
$sql = "SELECT COUNT(*) AS `object_cnt` FROM `object_count` WHERE `object_type`= ? AND `object_id` = ?"; $sql = "SELECT COUNT(*) AS `object_cnt` FROM `object_count` WHERE `object_type`= ? AND `object_id` = ?";
$db_results = Dba::read($sql, array($object_type, $object_id)); $db_results = Dba::read($sql, array($object_type, $object_id));
$results = Dba::fetch_assoc($db_results); $results = Dba::fetch_assoc($db_results);
return $results['object_cnt']; return $results['object_cnt'];
} // get_object_count } // get_object_count
@ -109,8 +111,8 @@ class Stats {
* if we should re-submit or if this is a duplicate / if it's too soon. This takes an * if we should re-submit or if this is a duplicate / if it's too soon. This takes an
* optional user_id because when streaming we don't have $GLOBALS() * optional user_id because when streaming we don't have $GLOBALS()
*/ */
public static function get_last_song($user_id='') { public static function get_last_song($user_id='')
{
$user_id = $user_id ? $user_id : $GLOBALS['user']->id; $user_id = $user_id ? $user_id : $GLOBALS['user']->id;
$sql = "SELECT * FROM `object_count` WHERE `user` = ? AND `object_type`='song' ORDER BY `date` DESC LIMIT 1"; $sql = "SELECT * FROM `object_count` WHERE `user` = ? AND `object_type`='song' ORDER BY `date` DESC LIMIT 1";
@ -127,8 +129,8 @@ class Stats {
* This returns the objects that have happened for $user_id sometime after $time * This returns the objects that have happened for $user_id sometime after $time
* used primarly by the democratic cooldown code * used primarly by the democratic cooldown code
*/ */
public static function get_object_history($user_id='',$time) { public static function get_object_history($user_id='',$time)
{
$user_id = $user_id ? $user_id : $GLOBALS['user']->id; $user_id = $user_id ? $user_id : $GLOBALS['user']->id;
$sql = "SELECT * FROM `object_count` WHERE `user` = ? AND `object_type`='song' AND `date` >= ? " . $sql = "SELECT * FROM `object_count` WHERE `user` = ? AND `object_type`='song' AND `date` >= ? " .
@ -150,8 +152,8 @@ class Stats {
* This returns the top X for type Y from the * This returns the top X for type Y from the
* last stats_threshold days * last stats_threshold days
*/ */
public static function get_top($type,$count='',$threshold = '',$offset='') { public static function get_top($type,$count='',$threshold = '',$offset='')
{
/* If they don't pass one, then use the preference */ /* If they don't pass one, then use the preference */
if (!$threshold) { if (!$threshold) {
$threshold = Config::get('stats_threshold'); $threshold = Config::get('stats_threshold');
@ -185,14 +187,14 @@ class Stats {
return $results; return $results;
} // get_top } // get_top
/** /**
* get_recent * get_recent
* This returns the recent X for type Y from the * This returns the recent X for type Y from the
* last stats_threshold days * last stats_threshold days
*/ */
public static function get_recent($type,$count='',$threshold = '',$offset='') { public static function get_recent($type,$count='',$threshold = '',$offset='')
{
/* If they don't pass one, then use the preference */ /* If they don't pass one, then use the preference */
if (!$threshold) { if (!$threshold) {
$threshold = Config::get('stats_threshold'); $threshold = Config::get('stats_threshold');
@ -230,16 +232,15 @@ class Stats {
* This gets all stats for atype based on user with thresholds and all * This gets all stats for atype based on user with thresholds and all
* If full is passed, doesn't limit based on date * If full is passed, doesn't limit based on date
*/ */
public static function get_user($count,$type,$user,$full='') { public static function get_user($count,$type,$user,$full='')
{
$count = intval($count); $count = intval($count);
$type = self::validate_type($type); $type = self::validate_type($type);
/* If full then don't limit on date */ /* If full then don't limit on date */
if ($full) { if ($full) {
$date = '0'; $date = '0';
} } else {
else {
$date = time() - (86400*Config::get('stats_threshold')); $date = time() - (86400*Config::get('stats_threshold'));
} }
@ -265,8 +266,8 @@ class Stats {
* This function takes a type and returns only those * This function takes a type and returns only those
* which are allowed, ensures good data gets put into the db * which are allowed, ensures good data gets put into the db
*/ */
public static function validate_type($type) { public static function validate_type($type)
{
switch ($type) { switch ($type) {
case 'artist': case 'artist':
case 'album': case 'album':
@ -286,8 +287,8 @@ class Stats {
* This returns an array of the newest artists/albums/whatever * This returns an array of the newest artists/albums/whatever
* in this ampache instance * in this ampache instance
*/ */
public static function get_newest($type,$limit='',$offset='') { public static function get_newest($type,$limit='',$offset='')
{
if (!$count) { $count = Config::get('popular_threshold'); } if (!$count) { $count = Config::get('popular_threshold'); }
if (!$offset) { if (!$offset) {
$limit = $count; $limit = $count;
@ -312,4 +313,3 @@ class Stats {
} // get_newest } // get_newest
} // Stats class } // Stats class
?>

View file

@ -21,13 +21,14 @@
*/ */
class Stream { class Stream
{
public static $session; public static $session;
private function __construct() { private function __construct()
{
// Static class, do nothing. // Static class, do nothing.
} }
/** /**
* set_session * set_session
@ -36,12 +37,13 @@ class Stream {
* an additional session into the database, should be called * an additional session into the database, should be called
* with care * with care
*/ */
public static function set_session($sid) { public static function set_session($sid)
{
self::$session=$sid; self::$session=$sid;
} // set_session } // set_session
public static function get_allowed_bitrate($song) { public static function get_allowed_bitrate($song)
{
$max_bitrate = Config::get('max_bit_rate'); $max_bitrate = Config::get('max_bit_rate');
$min_bitrate = Config::get('min_bit_rate'); $min_bitrate = Config::get('min_bit_rate');
// FIXME: This should be configurable for each output type // FIXME: This should be configurable for each output type
@ -51,9 +53,9 @@ class Stream {
if ($user_sample_rate < $min_bitrate) { if ($user_sample_rate < $min_bitrate) {
$min_bitrate = $user_sample_rate; $min_bitrate = $user_sample_rate;
} }
// Are there site-wide constraints? (Dynamic downsampling.) // Are there site-wide constraints? (Dynamic downsampling.)
if ($max_bitrate > 1 ) { if ($max_bitrate > 1) {
$sql = 'SELECT COUNT(*) FROM `now_playing` ' . $sql = 'SELECT COUNT(*) FROM `now_playing` ' .
'WHERE `user` IN ' . 'WHERE `user` IN ' .
'(SELECT DISTINCT `user_preference`.`user` ' . '(SELECT DISTINCT `user_preference`.`user` ' .
@ -90,7 +92,7 @@ class Stream {
else { else {
$sample_rate = $user_sample_rate; $sample_rate = $user_sample_rate;
} }
return $sample_rate; return $sample_rate;
} }
@ -100,7 +102,8 @@ class Stream {
* This is a rather complex function that starts the transcoding or * This is a rather complex function that starts the transcoding or
* resampling of a song and returns the opened file handle. * resampling of a song and returns the opened file handle.
*/ */
public static function start_transcode($song, $type = null) { public static function start_transcode($song, $type = null)
{
$transcode_settings = $song->get_transcode_settings($type); $transcode_settings = $song->get_transcode_settings($type);
// Bail out early if we're unutterably broken // Bail out early if we're unutterably broken
if ($transcode_settings == false) { if ($transcode_settings == false) {
@ -162,8 +165,8 @@ class Stream {
* validate_bitrate * validate_bitrate
* this function takes a bitrate and returns a valid one * this function takes a bitrate and returns a valid one
*/ */
public static function validate_bitrate($bitrate) { public static function validate_bitrate($bitrate)
{
/* Round to standard bitrates */ /* Round to standard bitrates */
$sample_rate = 16*(floor($bitrate/16)); $sample_rate = 16*(floor($bitrate/16));
@ -178,8 +181,8 @@ class Stream {
* This will garbage collect the now playing data, * This will garbage collect the now playing data,
* this is done on every play start. * this is done on every play start.
*/ */
public static function gc_now_playing() { public static function gc_now_playing()
{
// Remove any now playing entries for sessions that have been GC'd // Remove any now playing entries for sessions that have been GC'd
$sql = "DELETE FROM `now_playing` USING `now_playing` " . $sql = "DELETE FROM `now_playing` USING `now_playing` " .
"LEFT JOIN `session` ON `session`.`id` = `now_playing`.`id` " . "LEFT JOIN `session` ON `session`.`id` = `now_playing`.`id` " .
@ -193,7 +196,8 @@ class Stream {
* *
* This will insert the now playing data. * This will insert the now playing data.
*/ */
public static function insert_now_playing($oid, $uid, $length, $sid, $type) { public static function insert_now_playing($oid, $uid, $length, $sid, $type)
{
$time = intval(time() + $length); $time = intval(time() + $length);
$type = strtolower($type); $type = strtolower($type);
@ -210,7 +214,8 @@ class Stream {
* There really isn't anywhere else for this function, shouldn't have * There really isn't anywhere else for this function, shouldn't have
* deleted it in the first place. * deleted it in the first place.
*/ */
public static function clear_now_playing() { public static function clear_now_playing()
{
$sql = 'TRUNCATE `now_playing`'; $sql = 'TRUNCATE `now_playing`';
$db_results = Dba::write($sql); $db_results = Dba::write($sql);
@ -222,8 +227,8 @@ class Stream {
* *
* This returns the now playing information * This returns the now playing information
*/ */
public static function get_now_playing($filter=NULL) { public static function get_now_playing($filter=NULL)
{
$sql = 'SELECT `session`.`agent`, `now_playing`.* FROM `now_playing` ' . $sql = 'SELECT `session`.`agent`, `now_playing`.* FROM `now_playing` ' .
'LEFT JOIN `session` ON `session`.`id` = `now_playing`.`id` '; 'LEFT JOIN `session` ON `session`.`id` = `now_playing`.`id` ';
if (Config::get('now_playing_per_user')) { if (Config::get('now_playing_per_user')) {
@ -256,7 +261,8 @@ class Stream {
* *
* This checks to see if the media is already being played. * This checks to see if the media is already being played.
*/ */
public static function check_lock_media($media_id, $type) { public static function check_lock_media($media_id, $type)
{
$sql = 'SELECT `object_id` FROM `now_playing` WHERE ' . $sql = 'SELECT `object_id` FROM `now_playing` WHERE ' .
'`object_id` = ? AND `object_type` = ?'; '`object_id` = ? AND `object_type` = ?';
$db_results = Dba::read($sql, array($media_id, $type)); $db_results = Dba::read($sql, array($media_id, $type));
@ -273,7 +279,8 @@ class Stream {
* auto_init * auto_init
* This is called on class load it sets the session * This is called on class load it sets the session
*/ */
public static function _auto_init() { public static function _auto_init()
{
// Generate the session ID. This is slightly wasteful. // Generate the session ID. This is slightly wasteful.
self::$session = Session::create(array('type' => 'stream')); self::$session = Session::create(array('type' => 'stream'));
} }
@ -286,8 +293,8 @@ class Stream {
* playlist mojo. If something needs to happen this will echo the * playlist mojo. If something needs to happen this will echo the
* javascript required to cause a reload of the iframe. * javascript required to cause a reload of the iframe.
*/ */
public static function run_playlist_method() { public static function run_playlist_method()
{
// If this wasn't ajax included run away // If this wasn't ajax included run away
if (!defined('AJAX_INCLUDE')) { return false; } if (!defined('AJAX_INCLUDE')) { return false; }
@ -316,8 +323,8 @@ class Stream {
* get_base_url * get_base_url
* This returns the base requirements for a stream URL this does not include anything after the index.php?sid=???? * This returns the base requirements for a stream URL this does not include anything after the index.php?sid=????
*/ */
public static function get_base_url() { public static function get_base_url()
{
if (Config::get('require_session')) { if (Config::get('require_session')) {
$session_string = 'ssid=' . self::$session . '&'; $session_string = 'ssid=' . self::$session . '&';
} }
@ -330,8 +337,7 @@ class Stream {
if (Config::get('http_port') != '80') { if (Config::get('http_port') != '80') {
if (preg_match("/:(\d+)/",$web_path,$matches)) { if (preg_match("/:(\d+)/",$web_path,$matches)) {
$web_path = str_replace(':' . $matches['1'],':' . Config::get('http_port'),$web_path); $web_path = str_replace(':' . $matches['1'],':' . Config::get('http_port'),$web_path);
} } else {
else {
$web_path = str_replace($_SERVER['HTTP_HOST'],$_SERVER['HTTP_HOST'] . ':' . Config::get('http_port'),$web_path); $web_path = str_replace($_SERVER['HTTP_HOST'],$_SERVER['HTTP_HOST'] . ':' . Config::get('http_port'),$web_path);
} }
} }
@ -343,5 +349,3 @@ class Stream {
} // get_base_url } // get_base_url
} //end of stream class } //end of stream class
?>

View file

@ -28,18 +28,18 @@
* module in question. * module in question.
*/ */
class Stream_Playlist { class Stream_Playlist
{
public $id; public $id;
public $urls = array(); public $urls = array();
public $user; public $user;
/** /**
* Stream_Playlist constructor * Stream_Playlist constructor
* If an ID is passed, it should be a stream session ID. * If an ID is passed, it should be a stream session ID.
*/ */
public function __construct($id = null) { public function __construct($id = null)
{
if ($id) { if ($id) {
Stream::set_session($id); Stream::set_session($id);
} }
@ -63,7 +63,8 @@ class Stream_Playlist {
return true; return true;
} }
private function _add_url($url) { private function _add_url($url)
{
$this->urls[] = $url; $this->urls[] = $url;
$sql = 'INSERT INTO `stream_playlist` '; $sql = 'INSERT INTO `stream_playlist` ';
@ -85,7 +86,8 @@ class Stream_Playlist {
return Dba::write($sql, $values); return Dba::write($sql, $values);
} }
public static function gc() { public static function gc()
{
$sql = 'DELETE FROM `stream_playlist` USING `stream_playlist` ' . $sql = 'DELETE FROM `stream_playlist` USING `stream_playlist` ' .
'LEFT JOIN `session` ON `session`.`id`=`stream_playlist`.`sid` ' . 'LEFT JOIN `session` ON `session`.`id`=`stream_playlist`.`sid` ' .
'WHERE `session`.`id` IS NULL'; 'WHERE `session`.`id` IS NULL';
@ -96,9 +98,10 @@ class Stream_Playlist {
* _media_to_urlarray * _media_to_urlarray
* Formats the URL and media information and adds it to the object * Formats the URL and media information and adds it to the object
*/ */
private static function _media_to_urlarray($media) { private static function _media_to_urlarray($media)
{
$urls = array(); $urls = array();
foreach($media as $medium) { foreach ($media as $medium) {
debug_event('stream_playlist', 'Adding ' . json_encode($medium), 5); debug_event('stream_playlist', 'Adding ' . json_encode($medium), 5);
$url = array(); $url = array();
@ -113,7 +116,7 @@ class Stream_Playlist {
// Set a default which can be overridden // Set a default which can be overridden
$url['author'] = 'Ampache'; $url['author'] = 'Ampache';
$url['time'] = $object->time; $url['time'] = $object->time;
switch($type) { switch ($type) {
case 'song': case 'song':
$url['title'] = $object->title; $url['title'] = $object->title;
$url['author'] = $object->f_artist_full; $url['author'] = $object->f_artist_full;
@ -145,8 +148,8 @@ class Stream_Playlist {
return $urls; return $urls;
} }
public function generate_playlist($type, $redirect = false) { public function generate_playlist($type, $redirect = false)
{
if (!count($this->urls)) { if (!count($this->urls)) {
debug_event('stream_playlist', 'Error: Empty URL array for ' . $this->id, 2); debug_event('stream_playlist', 'Error: Empty URL array for ' . $this->id, 2);
return false; return false;
@ -155,7 +158,7 @@ class Stream_Playlist {
debug_event('stream_playlist', 'generating a ' . $type, 5); debug_event('stream_playlist', 'generating a ' . $type, 5);
$ext = $type; $ext = $type;
switch($type) { switch ($type) {
case 'download': case 'download':
case 'democratic': case 'democratic':
case 'localplay': case 'localplay':
@ -208,7 +211,8 @@ class Stream_Playlist {
* add * add
* Adds an array of media * Adds an array of media
*/ */
public function add($media = array()) { public function add($media = array())
{
$urls = $this->_media_to_urlarray($media); $urls = $this->_media_to_urlarray($media);
foreach ($urls as $url) { foreach ($urls as $url) {
$this->_add_url($url); $this->_add_url($url);
@ -220,8 +224,8 @@ class Stream_Playlist {
* Add an array of urls. This is used for things that aren't coming * Add an array of urls. This is used for things that aren't coming
* from media objects * from media objects
*/ */
public function add_urls($urls = array()) { public function add_urls($urls = array())
{
if (!is_array($urls)) { return false; } if (!is_array($urls)) { return false; }
foreach ($urls as $url) { foreach ($urls as $url) {
@ -238,8 +242,8 @@ class Stream_Playlist {
* create_simplem3u * create_simplem3u
* this creates a simple m3u without any of the extended information * this creates a simple m3u without any of the extended information
*/ */
public function create_simple_m3u() { public function create_simple_m3u()
{
foreach ($this->urls as $url) { foreach ($this->urls as $url) {
echo $url->url . "\n"; echo $url->url . "\n";
} }
@ -251,8 +255,8 @@ class Stream_Playlist {
* creates an m3u file, this includes the EXTINFO and as such can be * creates an m3u file, this includes the EXTINFO and as such can be
* large with very long playlsits * large with very long playlsits
*/ */
public function create_m3u() { public function create_m3u()
{
echo "#EXTM3U\n"; echo "#EXTM3U\n";
foreach ($this->urls as $url) { foreach ($this->urls as $url) {
@ -266,8 +270,8 @@ class Stream_Playlist {
/** /**
* create_pls * create_pls
*/ */
public function create_pls() { public function create_pls()
{
echo "[playlist]\n"; echo "[playlist]\n";
echo 'NumberOfEntries=' . count($this->urls) . "\n"; echo 'NumberOfEntries=' . count($this->urls) . "\n";
foreach ($this->urls as $url) { foreach ($this->urls as $url) {
@ -285,8 +289,8 @@ class Stream_Playlist {
* create_asx * create_asx
* This should really only be used if all of the content is ASF files. * This should really only be used if all of the content is ASF files.
*/ */
public function create_asx() { public function create_asx()
{
echo '<ASX VERSION="3.0" BANNERBAR="auto">' . "\n"; echo '<ASX VERSION="3.0" BANNERBAR="auto">' . "\n";
echo "<TITLE>Ampache ASX Playlist</TITLE>\n"; echo "<TITLE>Ampache ASX Playlist</TITLE>\n";
echo '<PARAM NAME="Encoding" VALUE="utf-8" />' . "\n"; echo '<PARAM NAME="Encoding" VALUE="utf-8" />' . "\n";
@ -311,8 +315,8 @@ class Stream_Playlist {
/** /**
* create_xspf * create_xspf
*/ */
public function create_xspf() { public function create_xspf()
{
foreach ($this->urls as $url) { foreach ($this->urls as $url) {
$xml = array(); $xml = array();
@ -324,7 +328,7 @@ class Stream_Playlist {
'identifier' => $url->url 'identifier' => $url->url
); );
if ($url->type == 'video') { if ($url->type == 'video') {
$xml['track']['meta'] = $xml['track']['meta'] =
array( array(
'attribute' => 'rel="provider"', 'attribute' => 'rel="provider"',
'value' => 'video' 'value' => 'video'
@ -356,22 +360,22 @@ class Stream_Playlist {
* *
* Creates an html5 player. * Creates an html5 player.
*/ */
public function create_html5_player() { public function create_html5_player()
{
if (Config::get("iframes")) { if (Config::get("iframes")) {
require Config::get('prefix') . '/templates/create_html5_player_embedded.inc.php'; require Config::get('prefix') . '/templates/create_html5_player_embedded.inc.php';
} else { } else {
require Config::get('prefix') . '/templates/create_html5_player.inc.php'; require Config::get('prefix') . '/templates/create_html5_player.inc.php';
} }
} // create_html5_player } // create_html5_player
/** /**
* create_localplay * create_localplay
* This calls the Localplay API to add the URLs and then start playback * This calls the Localplay API to add the URLs and then start playback
*/ */
public function create_localplay() { public function create_localplay()
{
$localplay = new Localplay(Config::get('localplay_controller')); $localplay = new Localplay(Config::get('localplay_controller'));
$localplay->connect(); $localplay->connect();
foreach ($this->urls as $url) { foreach ($this->urls as $url) {
@ -388,7 +392,8 @@ class Stream_Playlist {
* This 'votes' on the songs; it inserts them into a tmp_playlist with user * This 'votes' on the songs; it inserts them into a tmp_playlist with user
* set to -1. * set to -1.
*/ */
public function create_democratic() { public function create_democratic()
{
$democratic = Democratic::get_current_playlist(); $democratic = Democratic::get_current_playlist();
$democratic->set_parent(); $democratic->set_parent();
$items = array(); $items = array();
@ -405,8 +410,8 @@ class Stream_Playlist {
* create_download * create_download
* This prompts for a download of the song * This prompts for a download of the song
*/ */
private function create_download() { private function create_download()
{
// There should only be one here... // There should only be one here...
if (count($this->urls) != 1) { if (count($this->urls) != 1) {
debug_event('stream_playlist', 'Download called, but $urls contains ' . json_encode($this->urls), 2); debug_event('stream_playlist', 'Download called, but $urls contains ' . json_encode($this->urls), 2);
@ -422,10 +427,10 @@ class Stream_Playlist {
* create_ram * create_ram
*this functions creates a RAM file for use by Real Player *this functions creates a RAM file for use by Real Player
*/ */
public function create_ram() { public function create_ram()
{
foreach ($this->urls as $url) { foreach ($this->urls as $url) {
echo $url->url . "\n"; echo $url->url . "\n";
} }
} // create_ram } // create_ram
} }
?>

View file

@ -23,8 +23,8 @@
// A class for passing around an URL and associated data // A class for passing around an URL and associated data
class Stream_URL extends memory_object { class Stream_URL extends memory_object
{
public $properties = array('url', 'title', 'author', 'time', 'info_url', 'image_url', 'album', 'type'); public $properties = array('url', 'title', 'author', 'time', 'info_url', 'image_url', 'album', 'type');
/** /**
@ -32,7 +32,8 @@ class Stream_URL extends memory_object {
* *
* Takes an url and parses out all the chewy goodness. * Takes an url and parses out all the chewy goodness.
*/ */
public static function parse($url) { public static function parse($url)
{
$query = parse_url($url, PHP_URL_QUERY); $query = parse_url($url, PHP_URL_QUERY);
$elements = explode('&', $query); $elements = explode('&', $query);
$results = array(); $results = array();

File diff suppressed because it is too large Load diff

View file

@ -28,8 +28,8 @@
* are all static calls * are all static calls
* *
*/ */
class Subsonic_XML_Data { class Subsonic_XML_Data
{
const API_VERSION = "1.10.1"; const API_VERSION = "1.10.1";
const SSERROR_GENERIC = 0; const SSERROR_GENERIC = 0;
@ -40,78 +40,90 @@ class Subsonic_XML_Data {
const SSERROR_UNAUTHORIZED = 50; const SSERROR_UNAUTHORIZED = 50;
const SSERROR_TRIAL = 60; const SSERROR_TRIAL = 60;
const SSERROR_DATA_NOTFOUND = 70; const SSERROR_DATA_NOTFOUND = 70;
// Ampache doesn't have a global unique id but each items are unique per category. We use id pattern to identify item category. // Ampache doesn't have a global unique id but each items are unique per category. We use id pattern to identify item category.
const AMPACHEID_ARTIST = 100000000; const AMPACHEID_ARTIST = 100000000;
const AMPACHEID_ALBUM = 200000000; const AMPACHEID_ALBUM = 200000000;
const AMPACHEID_SONG = 300000000; const AMPACHEID_SONG = 300000000;
/** /**
* constructor * constructor
* *
* We don't use this, as its really a static class * We don't use this, as its really a static class
*/ */
private function __construct() { private function __construct()
{
} }
public static function getArtistId($id) { public static function getArtistId($id)
{
return $id + Subsonic_XML_Data::AMPACHEID_ARTIST; return $id + Subsonic_XML_Data::AMPACHEID_ARTIST;
} }
public static function getAlbumId($id) { public static function getAlbumId($id)
{
return $id + Subsonic_XML_Data::AMPACHEID_ALBUM; return $id + Subsonic_XML_Data::AMPACHEID_ALBUM;
} }
public static function getSongId($id) { public static function getSongId($id)
{
return $id + Subsonic_XML_Data::AMPACHEID_SONG; return $id + Subsonic_XML_Data::AMPACHEID_SONG;
} }
public static function getAmpacheId($id) { public static function getAmpacheId($id)
{
return ($id % Subsonic_XML_Data::AMPACHEID_ARTIST); return ($id % Subsonic_XML_Data::AMPACHEID_ARTIST);
} }
public static function getAmpacheIds($ids) { public static function getAmpacheIds($ids)
{
$ampids = array(); $ampids = array();
foreach ($ids as $id) { foreach ($ids as $id) {
$ampids[] = self::getAmpacheId($id); $ampids[] = self::getAmpacheId($id);
} }
return $ampids; return $ampids;
} }
public static function isArtist($id) { public static function isArtist($id)
{
return ($id >= Subsonic_XML_Data::AMPACHEID_ARTIST && $id < Subsonic_XML_Data::AMPACHEID_ALBUM); return ($id >= Subsonic_XML_Data::AMPACHEID_ARTIST && $id < Subsonic_XML_Data::AMPACHEID_ALBUM);
} }
public static function isAlbum($id) { public static function isAlbum($id)
{
return ($id >= Subsonic_XML_Data::AMPACHEID_ALBUM && $id < Subsonic_XML_Data::AMPACHEID_SONG); return ($id >= Subsonic_XML_Data::AMPACHEID_ALBUM && $id < Subsonic_XML_Data::AMPACHEID_SONG);
} }
public static function isSong($id) { public static function isSong($id)
{
return ($id >= Subsonic_XML_Data::AMPACHEID_SONG); return ($id >= Subsonic_XML_Data::AMPACHEID_SONG);
} }
public static function createFailedResponse($version = "") { public static function createFailedResponse($version = "")
{
$response = self::createResponse($version); $response = self::createResponse($version);
$response->addAttribute('status', 'failed'); $response->addAttribute('status', 'failed');
return $response; return $response;
} }
public static function createSuccessResponse($version = "") { public static function createSuccessResponse($version = "")
{
$response = self::createResponse($version); $response = self::createResponse($version);
$response->addAttribute('status', 'ok'); $response->addAttribute('status', 'ok');
return $response; return $response;
} }
public static function createResponse($version = "") { public static function createResponse($version = "")
{
if (empty($version)) $version = Subsonic_XML_Data::API_VERSION; if (empty($version)) $version = Subsonic_XML_Data::API_VERSION;
$response = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><subsonic-response/>'); $response = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><subsonic-response/>');
$response->addAttribute('xmlns', 'http://subsonic.org/restapi'); $response->addAttribute('xmlns', 'http://subsonic.org/restapi');
$response->addAttribute('version', $version); $response->addAttribute('version', $version);
return $response; return $response;
} }
public static function createError($code, $message = "", $version = "") { public static function createError($code, $message = "", $version = "")
{
if (empty($version)) $version = Subsonic_XML_Data::API_VERSION; if (empty($version)) $version = Subsonic_XML_Data::API_VERSION;
$response = self::createFailedResponse($version); $response = self::createFailedResponse($version);
self::setError($response, $code, $message); self::setError($response, $code, $message);
@ -125,11 +137,11 @@ class Subsonic_XML_Data {
* @param integer $code Error code * @param integer $code Error code
* @param string $string Error message * @param string $string Error message
*/ */
public static function setError($xml, $code, $message = "") { public static function setError($xml, $code, $message = "")
{
$xerr = $xml->addChild('error'); $xerr = $xml->addChild('error');
$xerr->addAttribute('code', $code); $xerr->addAttribute('code', $code);
if (empty($message)) { if (empty($message)) {
switch ($code) { switch ($code) {
case Subsonic_XML_Data::SSERROR_GENERIC: $message = "A generic error."; break; case Subsonic_XML_Data::SSERROR_GENERIC: $message = "A generic error."; break;
@ -142,40 +154,45 @@ class Subsonic_XML_Data {
case Subsonic_XML_Data::SSERROR_DATA_NOTFOUND: $message = "The requested data was not found."; break; case Subsonic_XML_Data::SSERROR_DATA_NOTFOUND: $message = "The requested data was not found."; break;
} }
} }
$xerr->addAttribute("message", $message); $xerr->addAttribute("message", $message);
} }
public static function addLicense($xml) { public static function addLicense($xml)
{
$xlic = $xml->addChild('license'); $xlic = $xml->addChild('license');
$xlic->addAttribute('valid', 'true'); $xlic->addAttribute('valid', 'true');
$xlic->addAttribute('email', 'webmaster@ampache.org'); $xlic->addAttribute('email', 'webmaster@ampache.org');
$xlic->addAttribute('key', 'ABC123DEF'); $xlic->addAttribute('key', 'ABC123DEF');
$xlic->addAttribute('date', '2009-09-03T14:46:43'); $xlic->addAttribute('date', '2009-09-03T14:46:43');
} }
public static function addMusicFolders($xml, $catalogs) { public static function addMusicFolders($xml, $catalogs)
{
$xfolders = $xml->addChild('musicFolders'); $xfolders = $xml->addChild('musicFolders');
foreach($catalogs as $id) { foreach ($catalogs as $id) {
$catalog = Catalog::create_from_id($id); $catalog = Catalog::create_from_id($id);
$xfolder = $xfolders->addChild('musicFolder'); $xfolder = $xfolders->addChild('musicFolder');
$xfolder->addAttribute('id', $id); $xfolder->addAttribute('id', $id);
$xfolder->addAttribute('name', $catalog->name); $xfolder->addAttribute('name', $catalog->name);
} }
} }
public static function addArtistsIndexes($xml, $artists, $lastModified) { public static function addArtistsIndexes($xml, $artists, $lastModified)
{
$xindexes = $xml->addChild('indexes'); $xindexes = $xml->addChild('indexes');
$xindexes->addAttribute('lastModified', $lastModified); $xindexes->addAttribute('lastModified', $lastModified);
self::addArtists($xindexes, $artists); self::addArtists($xindexes, $artists);
} }
public static function addArtistsRoot($xml, $artists) { public static function addArtistsRoot($xml, $artists)
{
$xartists = $xml->addChild('artists'); $xartists = $xml->addChild('artists');
self::addArtists($xartists, $artists, true); self::addArtists($xartists, $artists, true);
} }
public static function addArtists($xml, $artists, $extra=false) { public static function addArtists($xml, $artists, $extra=false)
{
$xlastcat = null; $xlastcat = null;
$xlastletter = ''; $xlastletter = '';
foreach ($artists as $artist) { foreach ($artists as $artist) {
@ -183,19 +200,20 @@ class Subsonic_XML_Data {
$letter = strtoupper($artist->name[0]); $letter = strtoupper($artist->name[0]);
if ($letter == "X" || $letter == "Y" || $letter == "Z") $letter = "X-Z"; if ($letter == "X" || $letter == "Y" || $letter == "Z") $letter = "X-Z";
else if (!preg_match("/^[A-W]$/", $letter)) $letter = "#"; else if (!preg_match("/^[A-W]$/", $letter)) $letter = "#";
if ($letter != $xlastletter) { if ($letter != $xlastletter) {
$xlastletter = $letter; $xlastletter = $letter;
$xlastcat = $xml->addChild('index'); $xlastcat = $xml->addChild('index');
$xlastcat->addAttribute('name', $xlastletter); $xlastcat->addAttribute('name', $xlastletter);
} }
} }
self::addArtist($xlastcat, $artist, $extra); self::addArtist($xlastcat, $artist, $extra);
} }
} }
public static function addArtist($xml, $artist, $extra=false, $albums=false) { public static function addArtist($xml, $artist, $extra=false, $albums=false)
{
$xartist = $xml->addChild('artist'); $xartist = $xml->addChild('artist');
$xartist->addAttribute('id', self::getArtistId($artist->id)); $xartist->addAttribute('id', self::getArtistId($artist->id));
$xartist->addAttribute('name', $artist->name); $xartist->addAttribute('name', $artist->name);
@ -212,15 +230,17 @@ class Subsonic_XML_Data {
} }
} }
public static function addAlbumList($xml, $albums, $elementName="albumList") { public static function addAlbumList($xml, $albums, $elementName="albumList")
{
$xlist = $xml->addChild($elementName); $xlist = $xml->addChild($elementName);
foreach($albums as $id) { foreach ($albums as $id) {
$album = new Album($id); $album = new Album($id);
self::addAlbum($xlist, $album); self::addAlbum($xlist, $album);
} }
} }
public static function addAlbum($xml, $album, $songs=false, $elementName="album") { public static function addAlbum($xml, $album, $songs=false, $elementName="album")
{
$xalbum = $xml->addChild($elementName); $xalbum = $xml->addChild($elementName);
$xalbum->addAttribute('id', self::getAlbumId($album->id)); $xalbum->addAttribute('id', self::getAlbumId($album->id));
$xalbum->addAttribute('album', $album->name); $xalbum->addAttribute('album', $album->name);
@ -234,11 +254,11 @@ class Subsonic_XML_Data {
$xalbum->addAttribute('artistId', self::getArtistId($album->artist_id)); $xalbum->addAttribute('artistId', self::getArtistId($album->artist_id));
$xalbum->addAttribute('parent', self::getArtistId($album->artist_id)); $xalbum->addAttribute('parent', self::getArtistId($album->artist_id));
$xalbum->addAttribute('artist', $album->artist_name); $xalbum->addAttribute('artist', $album->artist_name);
$rating = new Rating($album->id, "album"); $rating = new Rating($album->id, "album");
$rating_value = $rating->get_average_rating(); $rating_value = $rating->get_average_rating();
$xalbum->addAttribute('averageRating', ($rating_value) ? $rating_value : 0); $xalbum->addAttribute('averageRating', ($rating_value) ? $rating_value : 0);
if ($songs) { if ($songs) {
$allsongs = $album->get_songs(); $allsongs = $album->get_songs();
foreach ($allsongs as $id) { foreach ($allsongs as $id) {
@ -248,11 +268,13 @@ class Subsonic_XML_Data {
} }
} }
public static function addSong($xml, $song, $elementName='song') { public static function addSong($xml, $song, $elementName='song')
{
self::createSong($xml, $song, $elementName); self::createSong($xml, $song, $elementName);
} }
public static function createSong($xml, $song, $elementName='song') { public static function createSong($xml, $song, $elementName='song')
{
$xsong = $xml->addChild($elementName); $xsong = $xml->addChild($elementName);
$xsong->addAttribute('id', self::getSongId($song->id)); $xsong->addAttribute('id', self::getSongId($song->id));
$xsong->addAttribute('parent', self::getAlbumId($song->album)); $xsong->addAttribute('parent', self::getAlbumId($song->album));
@ -279,65 +301,72 @@ class Subsonic_XML_Data {
$xsong->addAttribute('suffix', $song->type); $xsong->addAttribute('suffix', $song->type);
$xsong->addAttribute('contentType', $song->mime); $xsong->addAttribute('contentType', $song->mime);
$xsong->addAttribute('path', $song->file); $xsong->addAttribute('path', $song->file);
//Do we need to support transcodedContentType and transcodedSuffix attributes? //Do we need to support transcodedContentType and transcodedSuffix attributes?
return $xsong; return $xsong;
} }
private static function formatAlbum($album) { private static function formatAlbum($album)
{
return $album->name . " [" . $album->year . "]"; return $album->name . " [" . $album->year . "]";
} }
public static function addArtistDirectory($xml, $artist) { public static function addArtistDirectory($xml, $artist)
{
$xdir = $xml->addChild('directory'); $xdir = $xml->addChild('directory');
$xdir->addAttribute('id', self::getArtistId($artist->id)); $xdir->addAttribute('id', self::getArtistId($artist->id));
$xdir->addAttribute('name', $artist->name); $xdir->addAttribute('name', $artist->name);
$allalbums = $artist->get_albums(); $allalbums = $artist->get_albums();
foreach ($allalbums as $id) { foreach ($allalbums as $id) {
$album = new Album($id); $album = new Album($id);
self::addAlbum($xdir, $album, false, "child"); self::addAlbum($xdir, $album, false, "child");
} }
} }
public static function addAlbumDirectory($xml, $album) { public static function addAlbumDirectory($xml, $album)
{
$xdir = $xml->addChild('directory'); $xdir = $xml->addChild('directory');
$xdir->addAttribute('id', self::getAlbumId($album->id)); $xdir->addAttribute('id', self::getAlbumId($album->id));
$xdir->addAttribute('name', self::formatAlbum($album)); $xdir->addAttribute('name', self::formatAlbum($album));
$album->format(); $album->format();
//$xdir->addAttribute('parent', self::getArtistId($album->artist_id)); //$xdir->addAttribute('parent', self::getArtistId($album->artist_id));
$allsongs = $album->get_songs(); $allsongs = $album->get_songs();
foreach ($allsongs as $id) { foreach ($allsongs as $id) {
$song = new Song($id); $song = new Song($id);
self::addSong($xdir, $song, "child"); self::addSong($xdir, $song, "child");
} }
} }
public static function addGenres($xml, $tags) { public static function addGenres($xml, $tags)
{
$xgenres = $xml->addChild('genres'); $xgenres = $xml->addChild('genres');
foreach($tags as $tag) { foreach ($tags as $tag) {
$otag = new Tag($tag['id']); $otag = new Tag($tag['id']);
$xgenre = $xgenres->addChild('genre', $otag->name); $xgenre = $xgenres->addChild('genre', $otag->name);
} }
} }
public static function addVideos($xml) { public static function addVideos($xml)
{
// Not supported yet // Not supported yet
$xvideos = $xml->addChild('videos'); $xvideos = $xml->addChild('videos');
} }
public static function addPlaylists($xml, $playlists) { public static function addPlaylists($xml, $playlists)
{
$xplaylists = $xml->addChild('playlists'); $xplaylists = $xml->addChild('playlists');
foreach($playlists as $id) { foreach ($playlists as $id) {
$playlist = new Playlist($id); $playlist = new Playlist($id);
self::addPlaylist($xplaylists, $playlist); self::addPlaylist($xplaylists, $playlist);
} }
} }
public static function addPlaylist($xml, $playlist, $songs=false) { public static function addPlaylist($xml, $playlist, $songs=false)
{
$xplaylist = $xml->addChild('playlist'); $xplaylist = $xml->addChild('playlist');
$xplaylist->addAttribute('id', $playlist->id); $xplaylist->addAttribute('id', $playlist->id);
$xplaylist->addAttribute('name', $playlist->name); $xplaylist->addAttribute('name', $playlist->name);
@ -347,25 +376,27 @@ class Subsonic_XML_Data {
$xplaylist->addAttribute('created', date("c", $playlist->date)); $xplaylist->addAttribute('created', date("c", $playlist->date));
$xplaylist->addAttribute('songCount', $playlist->get_song_count()); $xplaylist->addAttribute('songCount', $playlist->get_song_count());
$xplaylist->addAttribute('duration', $playlist->get_total_duration()); $xplaylist->addAttribute('duration', $playlist->get_total_duration());
if ($songs) { if ($songs) {
$allsongs = $playlist->get_songs(); $allsongs = $playlist->get_songs();
foreach($allsongs as $id) { foreach ($allsongs as $id) {
$song = new Song($id); $song = new Song($id);
self::addSong($xplaylist, $song, "entry"); self::addSong($xplaylist, $song, "entry");
} }
} }
} }
public static function addRandomSongs($xml, $songs) { public static function addRandomSongs($xml, $songs)
{
$xsongs = $xml->addChild('randomSongs'); $xsongs = $xml->addChild('randomSongs');
foreach ($songs as $id) { foreach ($songs as $id) {
$song = new Song($id); $song = new Song($id);
self::addSong($xsongs, $song); self::addSong($xsongs, $song);
} }
} }
public static function addSongsByGenre($xml, $songs) { public static function addSongsByGenre($xml, $songs)
{
$xsongs = $xml->addChild('songsByGenre'); $xsongs = $xml->addChild('songsByGenre');
foreach ($songs as $id) { foreach ($songs as $id) {
$song = new Song($id); $song = new Song($id);
@ -373,17 +404,19 @@ class Subsonic_XML_Data {
} }
} }
public static function addNowPlaying($xml, $data) { public static function addNowPlaying($xml, $data)
{
$xplaynow = $xml->addChild('nowPlaying'); $xplaynow = $xml->addChild('nowPlaying');
foreach($data as $d) { foreach ($data as $d) {
$track = self::createSong($xplaynow, $d['media'], "entry"); $track = self::createSong($xplaynow, $d['media'], "entry");
$track->addAttribute('username', $d['client']->username); $track->addAttribute('username', $d['client']->username);
$track->addAttribute('minutesAgo', intval(time() - ($d['expire'] - Config::get('stream_length')) / 1000)); $track->addAttribute('minutesAgo', intval(time() - ($d['expire'] - Config::get('stream_length')) / 1000));
$track->addAttribute('playerId', $d['agent']); $track->addAttribute('playerId', $d['agent']);
} }
} }
public static function addSearchResult($xml, $artists, $albums, $songs, $elementName = "searchResult2") { public static function addSearchResult($xml, $artists, $albums, $songs, $elementName = "searchResult2")
{
$xresult = $xml->addChild($elementName); $xresult = $xml->addChild($elementName);
foreach ($artists as $id) { foreach ($artists as $id) {
$artist = new Artist($id); $artist = new Artist($id);
@ -398,25 +431,24 @@ class Subsonic_XML_Data {
self::addSong($xresult, $song); self::addSong($xresult, $song);
} }
} }
public static function addStarred($xml, $artists, $albums, $songs, $elementName="starred") { public static function addStarred($xml, $artists, $albums, $songs, $elementName="starred")
{
$xstarred = $xml->addChild($elementName); $xstarred = $xml->addChild($elementName);
foreach ($artists as $id) { foreach ($artists as $id) {
$artist = new Artist($id); $artist = new Artist($id);
self::addArtist($xstarred, $artist); self::addArtist($xstarred, $artist);
} }
foreach ($albums as $id) { foreach ($albums as $id) {
$album = new Album($id); $album = new Album($id);
self::addAlbum($xstarred, $album); self::addAlbum($xstarred, $album);
} }
foreach ($songs as $id) { foreach ($songs as $id) {
$song = new Song($id); $song = new Song($id);
self::addSong($xstarred, $song); self::addSong($xstarred, $song);
} }
} }
} }
?>

View file

@ -26,8 +26,8 @@
* This class hnadles all of the tag relation operations * This class hnadles all of the tag relation operations
* *
*/ */
class Tag extends database_object { class Tag extends database_object
{
public $id; public $id;
public $name; public $name;
@ -40,8 +40,8 @@ class Tag extends database_object {
* constructor * constructor
* This takes a tag id and returns all of the relevent information * This takes a tag id and returns all of the relevent information
*/ */
public function __construct($id) { public function __construct($id)
{
if (!$id) { return false; } if (!$id) { return false; }
$info = $this->get_info($id); $info = $this->get_info($id);
@ -56,8 +56,8 @@ class Tag extends database_object {
* construct_from_name * construct_from_name
* This attempts to construct the tag from a name, rather then the ID * This attempts to construct the tag from a name, rather then the ID
*/ */
public static function construct_from_name($name) { public static function construct_from_name($name)
{
$tag_id = self::tag_exists($name); $tag_id = self::tag_exists($name);
$tag = new Tag($tag_id); $tag = new Tag($tag_id);
@ -71,8 +71,8 @@ class Tag extends database_object {
* This makes the tag presentable to the great humans that use this program, other life forms * This makes the tag presentable to the great humans that use this program, other life forms
* will just have to fend for themselves * will just have to fend for themselves
*/ */
public function format($type=0,$object_id=0) { public function format($type=0,$object_id=0)
{
if ($type AND !self::validate_type($type)) { return false; } if ($type AND !self::validate_type($type)) { return false; }
if ($type) { if ($type) {
@ -86,8 +86,7 @@ class Tag extends database_object {
if ($this->owner == $GLOBALS['user']->id) { if ($this->owner == $GLOBALS['user']->id) {
$action = '?page=tag&action=remove_tag&type=' . scrub_out($type) . '&tag_id=' . intval($this->id) . '&object_id=' . intval($object_id); $action = '?page=tag&action=remove_tag&type=' . scrub_out($type) . '&tag_id=' . intval($this->id) . '&object_id=' . intval($object_id);
$class = "hover-remove "; $class = "hover-remove ";
} } else {
else {
$action = '?page=tag&action=add_tag&type=' . scrub_out($type) . '&tag_id=' . intval($this->id) . '&object_id=' . intval($object_id); $action = '?page=tag&action=add_tag&type=' . scrub_out($type) . '&tag_id=' . intval($this->id) . '&object_id=' . intval($object_id);
$class = "hover-add "; $class = "hover-add ";
} }
@ -105,12 +104,11 @@ class Tag extends database_object {
* data from the map cache, otherwise I guess we'll just have to look it * data from the map cache, otherwise I guess we'll just have to look it
* up. * up.
*/ */
public function set_object($type,$object_id) { public function set_object($type,$object_id)
{
if (parent::is_cached('tag_top_' . $type,$object_id)) { if (parent::is_cached('tag_top_' . $type,$object_id)) {
$data = parent::get_from_cache('tag_top_' . $type,$object_id); $data = parent::get_from_cache('tag_top_' . $type,$object_id);
} } else {
else {
$data = self::get_top_tags($type,$object_id); $data = self::get_top_tags($type,$object_id);
} }
@ -132,8 +130,8 @@ class Tag extends database_object {
* This takes an array of object ids and caches all of their information * This takes an array of object ids and caches all of their information
* in a single query, cuts down on the connections * in a single query, cuts down on the connections
*/ */
public static function build_cache($ids) { public static function build_cache($ids)
{
if (!is_array($ids) OR !count($ids)) { return false; } if (!is_array($ids) OR !count($ids)) { return false; }
$idlist = '(' . implode(',',$ids) . ')'; $idlist = '(' . implode(',',$ids) . ')';
@ -152,8 +150,8 @@ class Tag extends database_object {
* build_map_cache * build_map_cache
* This builds a cache of the mappings for the specified object, no limit is given * This builds a cache of the mappings for the specified object, no limit is given
*/ */
public static function build_map_cache($type,$ids) { public static function build_map_cache($type,$ids)
{
if (!is_array($ids) OR !count($ids)) { return false; } if (!is_array($ids) OR !count($ids)) { return false; }
$type = self::validate_type($type); $type = self::validate_type($type);
@ -190,8 +188,8 @@ class Tag extends database_object {
* This is a wrapper function, it figures out what we need to add, be it a tag * This is a wrapper function, it figures out what we need to add, be it a tag
* and map, or just the mapping * and map, or just the mapping
*/ */
public static function add($type,$id,$value,$user=false) { public static function add($type,$id,$value,$user=false)
{
// Validate the tag type // Validate the tag type
if (!self::validate_type($type)) { return false; } if (!self::validate_type($type)) { return false; }
@ -226,8 +224,8 @@ class Tag extends database_object {
* add_tag * add_tag
* This function adds a new tag, for now we're going to limit the tagging a bit * This function adds a new tag, for now we're going to limit the tagging a bit
*/ */
public static function add_tag($value) { public static function add_tag($value)
{
// Clean it up and make it tagish // Clean it up and make it tagish
$value = self::clean_tag($value); $value = self::clean_tag($value);
@ -249,8 +247,8 @@ class Tag extends database_object {
* add_tag_map * add_tag_map
* This adds a specific tag to the map for specified object * This adds a specific tag to the map for specified object
*/ */
public static function add_tag_map($type,$object_id,$tag_id,$user='') { public static function add_tag_map($type,$object_id,$tag_id,$user='')
{
$uid = ($user == '') ? intval($GLOBALS['user']->id) : intval($user); $uid = ($user == '') ? intval($GLOBALS['user']->id) : intval($user);
$tag_id = intval($tag_id); $tag_id = intval($tag_id);
if (!self::validate_type($type)) { return false; } if (!self::validate_type($type)) { return false; }
@ -275,14 +273,15 @@ class Tag extends database_object {
* This cleans out tag_maps that are obsolete and then removes tags that * This cleans out tag_maps that are obsolete and then removes tags that
* have no maps. * have no maps.
*/ */
public static function gc() { public static function gc()
{
$sql = "DELETE FROM `tag_map` USING `tag_map` LEFT JOIN `song` ON `song`.`id`=`tag_map`.`object_id` " . $sql = "DELETE FROM `tag_map` USING `tag_map` LEFT JOIN `song` ON `song`.`id`=`tag_map`.`object_id` " .
"WHERE `tag_map`.`object_type`='song' AND `song`.`id` IS NULL"; "WHERE `tag_map`.`object_type`='song' AND `song`.`id` IS NULL";
$db_results = Dba::write($sql); $db_results = Dba::write($sql);
$sql = "DELETE FROM `tag_map` USING `tag_map` LEFT JOIN `album` ON `album`.`id`=`tag_map`.`object_id` " . $sql = "DELETE FROM `tag_map` USING `tag_map` LEFT JOIN `album` ON `album`.`id`=`tag_map`.`object_id` " .
"WHERE `tag_map`.`object_type`='album' AND `album`.`id` IS NULL"; "WHERE `tag_map`.`object_type`='album' AND `album`.`id` IS NULL";
$db_results = Dba::write($sql); $db_results = Dba::write($sql);
$sql = "DELETE FROM `tag_map` USING `tag_map` LEFT JOIN `artist` ON `artist`.`id`=`tag_map`.`object_id` " . $sql = "DELETE FROM `tag_map` USING `tag_map` LEFT JOIN `artist` ON `artist`.`id`=`tag_map`.`object_id` " .
"WHERE `tag_map`.`object_type`='artist' AND `artist`.`id` IS NULL"; "WHERE `tag_map`.`object_type`='artist' AND `artist`.`id` IS NULL";
@ -302,8 +301,8 @@ class Tag extends database_object {
* tag_exists * tag_exists
* This checks to see if a tag exists, this has nothing to do with objects or maps * This checks to see if a tag exists, this has nothing to do with objects or maps
*/ */
public static function tag_exists($value) { public static function tag_exists($value)
{
if (parent::is_cached('tag_name',$value)) { if (parent::is_cached('tag_name',$value)) {
return parent::get_from_cache('tag_name',$value); return parent::get_from_cache('tag_name',$value);
} }
@ -325,8 +324,8 @@ class Tag extends database_object {
* This looks to see if the current mapping of the current object of the current tag of the current * This looks to see if the current mapping of the current object of the current tag of the current
* user exists, lots of currents... taste good in scones. * user exists, lots of currents... taste good in scones.
*/ */
public static function tag_map_exists($type,$object_id,$tag_id,$user) { public static function tag_map_exists($type,$object_id,$tag_id,$user)
{
if (!self::validate_type($type)) { return false; } if (!self::validate_type($type)) { return false; }
if (parent::is_cached('tag_map_' . $type,$object_id)) { if (parent::is_cached('tag_map_' . $type,$object_id)) {
@ -354,8 +353,8 @@ class Tag extends database_object {
* get_top_tags * get_top_tags
* This gets the top tags for the specified object using limit * This gets the top tags for the specified object using limit
*/ */
public static function get_top_tags($type, $object_id, $limit = 10) { public static function get_top_tags($type, $object_id, $limit = 10)
{
if (!self::validate_type($type)) { return false; } if (!self::validate_type($type)) { return false; }
if (parent::is_cached('tag_top_' . $type,$object_id)) { if (parent::is_cached('tag_top_' . $type,$object_id)) {
@ -387,8 +386,8 @@ class Tag extends database_object {
* Display all tags that apply to maching target type of the specified id * Display all tags that apply to maching target type of the specified id
* UNUSED * UNUSED
*/ */
public static function get_object_tags($type, $id) { public static function get_object_tags($type, $id)
{
if (!self::validate_type($type)) { return array(); } if (!self::validate_type($type)) { return array(); }
$id = Dba::escape($id); $id = Dba::escape($id);
@ -412,10 +411,10 @@ class Tag extends database_object {
* get_tag_objects * get_tag_objects
* This gets the objects from a specified tag and returns an array of object ids, nothing more * This gets the objects from a specified tag and returns an array of object ids, nothing more
*/ */
public static function get_tag_objects($type,$tag_id,$count='',$offset='') { public static function get_tag_objects($type,$tag_id,$count='',$offset='')
{
if (!self::validate_type($type)) { return array(); } if (!self::validate_type($type)) { return array(); }
if ($count) { if ($count) {
$limit_sql = "LIMIT "; $limit_sql = "LIMIT ";
if ($offset) $limit_sql .= intval($offset) . ','; if ($offset) $limit_sql .= intval($offset) . ',';
@ -442,8 +441,8 @@ class Tag extends database_object {
* This is a non-object non type depedent function that just returns tags * This is a non-object non type depedent function that just returns tags
* we've got, it can take filters (this is used by the tag cloud) * we've got, it can take filters (this is used by the tag cloud)
*/ */
public static function get_tags($limit = 0,$filters=array()) { public static function get_tags($limit = 0,$filters=array())
{
$sql = "SELECT `tag_map`.`tag_id`,COUNT(`tag_map`.`object_id`) AS `count` " . $sql = "SELECT `tag_map`.`tag_id`,COUNT(`tag_map`.`object_id`) AS `count` " .
"FROM `tag_map` " . "FROM `tag_map` " .
"LEFT JOIN `tag` ON `tag`.`id`=`tag_map`.`tag_id` " . "LEFT JOIN `tag` ON `tag`.`id`=`tag_map`.`tag_id` " .
@ -474,8 +473,8 @@ class Tag extends database_object {
* it also takes a type so that it knows how to return it, this is used * it also takes a type so that it knows how to return it, this is used
* by the formating functions of the different objects * by the formating functions of the different objects
*/ */
public static function get_display($tags,$element_id,$type='song') { public static function get_display($tags,$element_id,$type='song')
{
if (!is_array($tags)) { return ''; } if (!is_array($tags)) { return ''; }
$results = ''; $results = '';
@ -498,8 +497,8 @@ class Tag extends database_object {
* This returns the count for the all objects associated with this tag * This returns the count for the all objects associated with this tag
* If a type is specific only counts for said type are returned * If a type is specific only counts for said type are returned
*/ */
public function count($type='') { public function count($type='')
{
if ($type) { if ($type) {
$filter_sql = " AND `object_type`='" . Dba::escape($type) . "'"; $filter_sql = " AND `object_type`='" . Dba::escape($type) . "'";
} }
@ -521,8 +520,8 @@ class Tag extends database_object {
* filter_with_prefs * filter_with_prefs
* This filters the tags based on the users preference * This filters the tags based on the users preference
*/ */
public static function filter_with_prefs($l) { public static function filter_with_prefs($l)
{
$colors = array('#0000FF', $colors = array('#0000FF',
'#00FF00', '#FFFF00', '#00FFFF','#FF00FF','#FF0000'); '#00FF00', '#FFFF00', '#00FFFF','#FF00FF','#FF0000');
$prefs = 'tag company'; $prefs = 'tag company';
@ -531,7 +530,7 @@ class Tag extends database_object {
$ulist = explode(' ', $prefs); $ulist = explode(' ', $prefs);
$req = ''; $req = '';
foreach($ulist as $i) { foreach ($ulist as $i) {
$req .= "'" . Dba::escape($i) . "',"; $req .= "'" . Dba::escape($i) . "',";
} }
$req = rtrim($req, ','); $req = rtrim($req, ',');
@ -540,8 +539,7 @@ class Tag extends database_object {
if ($prefs=='all') { if ($prefs=='all') {
$sql .= '1'; $sql .= '1';
} } else {
else {
$sql .= 'username in ('.$req.')'; $sql .= 'username in ('.$req.')';
} }
@ -564,8 +562,7 @@ class Tag extends database_object {
foreach ($l as $i) { foreach ($l as $i) {
if ($GLOBALS['user']->id == $i['user']) { if ($GLOBALS['user']->id == $i['user']) {
$res[] = $i; $res[] = $i;
} } elseif (isset($uids[$i['user']])) {
elseif (isset($uids[$i['user']])) {
$i['color'] = $uids[$i['user']]; $i['color'] = $uids[$i['user']];
$i['username'] = $usernames[$i['user']]; $i['username'] = $usernames[$i['user']];
$res[] = $i; $res[] = $i;
@ -580,8 +577,8 @@ class Tag extends database_object {
* remove_map * remove_map
* This will only remove tag maps for the current user * This will only remove tag maps for the current user
*/ */
public function remove_map($type,$object_id) { public function remove_map($type,$object_id)
{
if (!self::validate_type($type)) { return false; } if (!self::validate_type($type)) { return false; }
$type = Dba::escape($type); $type = Dba::escape($type);
@ -601,8 +598,8 @@ class Tag extends database_object {
* This validates the type of the object the user wants to tag, we limit this to types * This validates the type of the object the user wants to tag, we limit this to types
* we currently support * we currently support
*/ */
public static function validate_type($type) { public static function validate_type($type)
{
$valid_array = array('song','artist','album','video','playlist','live_stream'); $valid_array = array('song','artist','album','video','playlist','live_stream');
if (in_array($type,$valid_array)) { return $type; } if (in_array($type,$valid_array)) { return $type; }
@ -615,8 +612,8 @@ class Tag extends database_object {
* clean_tag * clean_tag
* This takes a string and makes it Tagish * This takes a string and makes it Tagish
*/ */
public static function clean_tag($value) { public static function clean_tag($value)
{
$tag = preg_replace("/[^\w\_\-\s\&]/","",$value); $tag = preg_replace("/[^\w\_\-\s\&]/","",$value);
return $tag; return $tag;
@ -624,4 +621,3 @@ class Tag extends database_object {
} // clean_tag } // clean_tag
} // end of Tag class } // end of Tag class
?>

View file

@ -28,8 +28,8 @@
* visit user_vote from time to time. * visit user_vote from time to time.
* *
*/ */
class Tmp_Playlist extends database_object { class Tmp_Playlist extends database_object
{
/* Variables from the Datbase */ /* Variables from the Datbase */
public $id; public $id;
public $session; public $session;
@ -46,8 +46,8 @@ class Tmp_Playlist extends database_object {
* information. If no playlist_id is passed or the requested one isn't * information. If no playlist_id is passed or the requested one isn't
* found, return false. * found, return false.
*/ */
public function __construct($playlist_id='') { public function __construct($playlist_id='')
{
if (!$playlist_id) { return false; } if (!$playlist_id) { return false; }
$this->id = intval($playlist_id); $this->id = intval($playlist_id);
@ -66,8 +66,8 @@ class Tmp_Playlist extends database_object {
* This is an internal (private) function that gathers the information * This is an internal (private) function that gathers the information
* for this object from the playlist_id that was passed in. * for this object from the playlist_id that was passed in.
*/ */
private function _get_info() { private function _get_info()
{
$sql = "SELECT * FROM `tmp_playlist` WHERE `id`='" . Dba::escape($this->id) . "'"; $sql = "SELECT * FROM `tmp_playlist` WHERE `id`='" . Dba::escape($this->id) . "'";
$db_results = Dba::read($sql); $db_results = Dba::read($sql);
@ -82,8 +82,8 @@ class Tmp_Playlist extends database_object {
* This returns a playlist object based on the session that is passed to * This returns a playlist object based on the session that is passed to
* us. This is used by the load_playlist on user for the most part. * us. This is used by the load_playlist on user for the most part.
*/ */
public static function get_from_session($session_id) { public static function get_from_session($session_id)
{
$session_id = Dba::escape($session_id); $session_id = Dba::escape($session_id);
$sql = "SELECT `id` FROM `tmp_playlist` WHERE `session`='$session_id'"; $sql = "SELECT `id` FROM `tmp_playlist` WHERE `session`='$session_id'";
@ -110,10 +110,10 @@ class Tmp_Playlist extends database_object {
* This returns a tmp playlist object based on a userid passed * This returns a tmp playlist object based on a userid passed
* this is used for the user profiles page * this is used for the user profiles page
*/ */
public static function get_from_userid($user_id) { public static function get_from_userid($user_id)
{
// This is a little stupid, but because we don't have the // This is a little stupid, but because we don't have the
// user_id in the session or in the tmp_playlist table we have // user_id in the session or in the tmp_playlist table we have
// to do it this way. // to do it this way.
$client = new User($user_id); $client = new User($user_id);
$username = Dba::escape($client->username); $username = Dba::escape($client->username);
@ -135,8 +135,8 @@ class Tmp_Playlist extends database_object {
* get_items * get_items
* Returns an array of all object_ids currently in this Tmp_Playlist. * Returns an array of all object_ids currently in this Tmp_Playlist.
*/ */
public function get_items() { public function get_items()
{
$id = Dba::escape($this->id); $id = Dba::escape($this->id);
/* Select all objects from this playlist */ /* Select all objects from this playlist */
@ -164,8 +164,8 @@ class Tmp_Playlist extends database_object {
* get_next_object * get_next_object
* This returns the next object in the tmp_playlist. * This returns the next object in the tmp_playlist.
*/ */
public function get_next_object() { public function get_next_object()
{
$id = Dba::escape($this->id); $id = Dba::escape($this->id);
$sql = "SELECT `object_id` FROM `tmp_playlist_data` " . $sql = "SELECT `object_id` FROM `tmp_playlist_data` " .
@ -183,8 +183,8 @@ class Tmp_Playlist extends database_object {
* This returns a count of the total number of tracks that are in this * This returns a count of the total number of tracks that are in this
* tmp playlist * tmp playlist
*/ */
public function count_items() { public function count_items()
{
$id = Dba::escape($this->id); $id = Dba::escape($this->id);
$sql = "SELECT COUNT(`id`) FROM `tmp_playlist_data` WHERE " . $sql = "SELECT COUNT(`id`) FROM `tmp_playlist_data` WHERE " .
@ -201,8 +201,8 @@ class Tmp_Playlist extends database_object {
* clear * clear
* This clears all the objects out of a single playlist * This clears all the objects out of a single playlist
*/ */
public function clear() { public function clear()
{
$id = Dba::escape($this->id); $id = Dba::escape($this->id);
$sql = "DELETE FROM `tmp_playlist_data` WHERE " . $sql = "DELETE FROM `tmp_playlist_data` WHERE " .
@ -216,11 +216,11 @@ class Tmp_Playlist extends database_object {
/** /**
* create * create
* This function initializes a new Tmp_Playlist. It is associated with * This function initializes a new Tmp_Playlist. It is associated with
* the current session rather than a user, as you could have the same * the current session rather than a user, as you could have the same
* user logged in from multiple locations. * user logged in from multiple locations.
*/ */
public static function create($data) { public static function create($data)
{
$sessid = Dba::escape($data['session_id']); $sessid = Dba::escape($data['session_id']);
$type = Dba::escape($data['type']); $type = Dba::escape($data['type']);
$object_type = Dba::escape($data['object_type']); $object_type = Dba::escape($data['object_type']);
@ -243,8 +243,8 @@ class Tmp_Playlist extends database_object {
* update_playlist * update_playlist
* This updates the base_playlist on this tmp_playlist * This updates the base_playlist on this tmp_playlist
*/ */
public function update_playlist($playlist_id) { public function update_playlist($playlist_id)
{
$playlist_id = Dba::escape($playlist_id); $playlist_id = Dba::escape($playlist_id);
$id = Dba::escape($this->id); $id = Dba::escape($this->id);
@ -261,8 +261,8 @@ class Tmp_Playlist extends database_object {
* This deletes any other tmp_playlists associated with this * This deletes any other tmp_playlists associated with this
* session * session
*/ */
public static function session_clean($sessid, $id) { public static function session_clean($sessid, $id)
{
$sessid = Dba::escape($sessid); $sessid = Dba::escape($sessid);
$id = Dba::escape($id); $id = Dba::escape($id);
@ -281,7 +281,8 @@ class Tmp_Playlist extends database_object {
* gc * gc
* This cleans up old data * This cleans up old data
*/ */
public static function gc() { public static function gc()
{
self::prune_playlists(); self::prune_playlists();
self::prune_tracks(); self::prune_tracks();
Dba::write("DELETE FROM `tmp_playlist_data` USING `tmp_playlist_data` LEFT JOIN `song` ON `tmp_playlist_data`.`object_id` = `song`.`id` WHERE `song`.`id` IS NULL"); Dba::write("DELETE FROM `tmp_playlist_data` USING `tmp_playlist_data` LEFT JOIN `song` ON `tmp_playlist_data`.`object_id` = `song`.`id` WHERE `song`.`id` IS NULL");
@ -291,8 +292,8 @@ class Tmp_Playlist extends database_object {
* prune_playlists * prune_playlists
* This deletes any playlists that don't have an associated session * This deletes any playlists that don't have an associated session
*/ */
public static function prune_playlists() { public static function prune_playlists()
{
/* Just delete if no matching session row */ /* Just delete if no matching session row */
$sql = "DELETE FROM `tmp_playlist` USING `tmp_playlist` " . $sql = "DELETE FROM `tmp_playlist` USING `tmp_playlist` " .
"LEFT JOIN `session` " . "LEFT JOIN `session` " .
@ -309,9 +310,9 @@ class Tmp_Playlist extends database_object {
* prune_tracks * prune_tracks
* This prunes tracks that don't have playlists or don't have votes * This prunes tracks that don't have playlists or don't have votes
*/ */
public static function prune_tracks() { public static function prune_tracks()
{
// This prune is always run and clears data for playlists that // This prune is always run and clears data for playlists that
// don't exist anymore // don't exist anymore
$sql = "DELETE FROM `tmp_playlist_data` USING " . $sql = "DELETE FROM `tmp_playlist_data` USING " .
"`tmp_playlist_data` LEFT JOIN `tmp_playlist` ON " . "`tmp_playlist_data` LEFT JOIN `tmp_playlist` ON " .
@ -326,8 +327,8 @@ class Tmp_Playlist extends database_object {
* This adds the object of $this->object_type to this tmp playlist * This adds the object of $this->object_type to this tmp playlist
* it takes an optional type, default is song * it takes an optional type, default is song
*/ */
public function add_object($object_id,$object_type) { public function add_object($object_id,$object_type)
{
$object_id = Dba::escape($object_id); $object_id = Dba::escape($object_id);
$playlist_id = Dba::escape($this->id); $playlist_id = Dba::escape($this->id);
$object_type = $object_type ? Dba::escape($object_type) : 'song'; $object_type = $object_type ? Dba::escape($object_type) : 'song';
@ -346,8 +347,8 @@ class Tmp_Playlist extends database_object {
* This checks to see if this playlist is a voting playlist * This checks to see if this playlist is a voting playlist
* and if it is active * and if it is active
*/ */
public function vote_active() { public function vote_active()
{
/* Going to do a little more here later */ /* Going to do a little more here later */
if ($this->type == 'vote') { return true; } if ($this->type == 'vote') { return true; }
@ -359,8 +360,8 @@ class Tmp_Playlist extends database_object {
* delete_track * delete_track
* This deletes a track from the tmpplaylist * This deletes a track from the tmpplaylist
*/ */
public function delete_track($id) { public function delete_track($id)
{
$id = Dba::escape($id); $id = Dba::escape($id);
/* delete the track its self */ /* delete the track its self */

View file

@ -23,13 +23,14 @@
// A collection of methods related to the user interface // A collection of methods related to the user interface
class UI { class UI
{
private static $_classes; private static $_classes;
private static $_ticker; private static $_ticker;
private static $_icon_cache; private static $_icon_cache;
public function __construct($data) { public function __construct($data)
{
return false; return false;
} }
@ -38,7 +39,8 @@ class UI {
* *
* Throw an error when they try to do something naughty. * Throw an error when they try to do something naughty.
*/ */
public static function access_denied($error = 'Access Denied') { public static function access_denied($error = 'Access Denied')
{
// Clear any buffered crap // Clear any buffered crap
ob_end_clean(); ob_end_clean();
header("HTTP/1.1 403 $error"); header("HTTP/1.1 403 $error");
@ -52,7 +54,8 @@ class UI {
* Does some trickery with the output buffer to return the output of a * Does some trickery with the output buffer to return the output of a
* template. * template.
*/ */
public static function ajax_include($template) { public static function ajax_include($template)
{
ob_start(); ob_start();
require Config::get('prefix') . '/templates/' . $template; require Config::get('prefix') . '/templates/' . $template;
$output = ob_get_contents(); $output = ob_get_contents();
@ -66,7 +69,8 @@ class UI {
* *
* Checks to see whether iconv is available; * Checks to see whether iconv is available;
*/ */
public static function check_iconv() { public static function check_iconv()
{
if (function_exists('iconv') && function_exists('iconv_substr')) { if (function_exists('iconv') && function_exists('iconv_substr')) {
return true; return true;
} }
@ -79,7 +83,8 @@ class UI {
* Stupid little cutesie thing to ratelimit output of long-running * Stupid little cutesie thing to ratelimit output of long-running
* operations. * operations.
*/ */
public static function check_ticker() { public static function check_ticker()
{
if (!isset(self::$_ticker) || (time() > self::$_ticker + 1)) { if (!isset(self::$_ticker) || (time() > self::$_ticker + 1)) {
self::$_ticker = time(); self::$_ticker = time();
return true; return true;
@ -95,10 +100,11 @@ class UI {
* UTF-8, but close enough for our purposes.) * UTF-8, but close enough for our purposes.)
* See http://www.w3.org/TR/2006/REC-xml-20060816/#charsets * See http://www.w3.org/TR/2006/REC-xml-20060816/#charsets
*/ */
public static function clean_utf8($string) { public static function clean_utf8($string)
{
if ($string) { if ($string) {
$clean = preg_replace('/[^\x{9}\x{a}\x{d}\x{20}-\x{d7ff}\x{e000}-\x{fffd}\x{10000}-\x{10ffff}]|[\x{7f}-\x{84}\x{86}-\x{9f}\x{fdd0}-\x{fddf}\x{1fffe}-\x{1ffff}\x{2fffe}-\x{2ffff}\x{3fffe}-\x{3ffff}\x{4fffe}-\x{4ffff}\x{5fffe}-\x{5ffff}\x{6fffe}-\x{6ffff}\x{7fffe}-\x{7ffff}\x{8fffe}-\x{8ffff}\x{9fffe}-\x{9ffff}\x{afffe}-\x{affff}\x{bfffe}-\x{bffff}\x{cfffe}-\x{cffff}\x{dfffe}-\x{dffff}\x{efffe}-\x{effff}\x{ffffe}-\x{fffff}\x{10fffe}-\x{10ffff}]/u', '', $string); $clean = preg_replace('/[^\x{9}\x{a}\x{d}\x{20}-\x{d7ff}\x{e000}-\x{fffd}\x{10000}-\x{10ffff}]|[\x{7f}-\x{84}\x{86}-\x{9f}\x{fdd0}-\x{fddf}\x{1fffe}-\x{1ffff}\x{2fffe}-\x{2ffff}\x{3fffe}-\x{3ffff}\x{4fffe}-\x{4ffff}\x{5fffe}-\x{5ffff}\x{6fffe}-\x{6ffff}\x{7fffe}-\x{7ffff}\x{8fffe}-\x{8ffff}\x{9fffe}-\x{9ffff}\x{afffe}-\x{affff}\x{bfffe}-\x{bffff}\x{cfffe}-\x{cffff}\x{dfffe}-\x{dffff}\x{efffe}-\x{effff}\x{ffffe}-\x{fffff}\x{10fffe}-\x{10ffff}]/u', '', $string);
if ($clean) { if ($clean) {
return $clean; return $clean;
} }
@ -113,11 +119,11 @@ class UI {
* First initialised with an array of two class names. Subsequent calls * First initialised with an array of two class names. Subsequent calls
* reverse the array then return the first element. * reverse the array then return the first element.
*/ */
public static function flip_class($classes = null) { public static function flip_class($classes = null)
{
if (is_array($classes)) { if (is_array($classes)) {
self::$_classes = $classes; self::$_classes = $classes;
} } else {
else {
self::$_classes = array_reverse(self::$_classes); self::$_classes = array_reverse(self::$_classes);
} }
return self::$_classes[0]; return self::$_classes[0];
@ -128,7 +134,8 @@ class UI {
* *
* Turns a size in bytes into the best human-readable value * Turns a size in bytes into the best human-readable value
*/ */
public static function format_bytes($value, $precision = 2) { public static function format_bytes($value, $precision = 2)
{
$pass = 0; $pass = 0;
while (strlen(floor($value)) > 3) { while (strlen(floor($value)) > 3) {
$value /= 1024; $value /= 1024;
@ -152,16 +159,16 @@ class UI {
* *
* Parses a human-readable size * Parses a human-readable size
*/ */
public static function unformat_bytes($value) { public static function unformat_bytes($value)
{
if (preg_match('/^([0-9]+) *([[:alpha:]]+)$/', $value, $matches)) { if (preg_match('/^([0-9]+) *([[:alpha:]]+)$/', $value, $matches)) {
$value = $matches[1]; $value = $matches[1];
$unit = strtolower(substr($matches[2], 0, 1)); $unit = strtolower(substr($matches[2], 0, 1));
} } else {
else {
return $value; return $value;
} }
switch($unit) { switch ($unit) {
case 'p': case 'p':
$value *= 1024; $value *= 1024;
case 't': case 't':
@ -182,7 +189,8 @@ class UI {
* *
* Returns an <img> tag for the specified icon * Returns an <img> tag for the specified icon
*/ */
public static function get_icon($name, $title = null, $id = null) { public static function get_icon($name, $title = null, $id = null)
{
if (is_array($name)) { if (is_array($name)) {
$hover_name = $name[1]; $hover_name = $name[1];
$name = $name[0]; $name = $name[0];
@ -218,7 +226,8 @@ class UI {
* *
* Does the finding icon thing * Does the finding icon thing
*/ */
private static function _find_icon($name) { private static function _find_icon($name)
{
if ($url = self::$_icon_cache[$name]) { if ($url = self::$_icon_cache[$name]) {
return $url; return $url;
} }
@ -230,7 +239,7 @@ class UI {
} }
$url = Config::get('web_path') . $path . $filename; $url = Config::get('web_path') . $path . $filename;
self::$_icon_cache[$name] = $url; self::$_icon_cache[$name] = $url;
return $url; return $url;
} }
@ -240,7 +249,8 @@ class UI {
* *
* For now this just shows the header template * For now this just shows the header template
*/ */
public static function show_header() { public static function show_header()
{
require_once Config::get('prefix') . '/templates/header.inc.php'; require_once Config::get('prefix') . '/templates/header.inc.php';
} }
@ -249,7 +259,8 @@ class UI {
* *
* For now this just shows the mainframes template * For now this just shows the mainframes template
*/ */
public static function show_mainframes() { public static function show_mainframes()
{
require_once Config::get('prefix') . '/templates/mainframes.inc.php'; require_once Config::get('prefix') . '/templates/mainframes.inc.php';
} }
@ -258,7 +269,8 @@ class UI {
* *
* Shows the footer template and possibly profiling info. * Shows the footer template and possibly profiling info.
*/ */
public static function show_footer() { public static function show_footer()
{
require_once Config::get('prefix') . '/templates/footer.inc.php'; require_once Config::get('prefix') . '/templates/footer.inc.php';
if (isset($_REQUEST['profiling'])) { if (isset($_REQUEST['profiling'])) {
Dba::show_profile(); Dba::show_profile();
@ -270,7 +282,8 @@ class UI {
* *
* This shows the top of the box. * This shows the top of the box.
*/ */
public static function show_box_top($title = '', $class = '') { public static 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';
} }
@ -279,7 +292,8 @@ class UI {
* *
* This shows the bottom of the box * This shows the bottom of the box
*/ */
public static function show_box_bottom() { public static function show_box_bottom()
{
require Config::get('prefix') . '/templates/show_box_bottom.inc.php'; require Config::get('prefix') . '/templates/show_box_bottom.inc.php';
} }
@ -289,7 +303,8 @@ class UI {
* Limit text to a certain length; adds an ellipsis if truncation was * Limit text to a certain length; adds an ellipsis if truncation was
* required. * required.
*/ */
public static function truncate($text, $max = 27) { public static function truncate($text, $max = 27)
{
// If they want <3, we're having none of that // If they want <3, we're having none of that
if ($max <= 3) { if ($max <= 3) {
debug_event('UI', "truncate called with $max, refusing to do stupid things to $text", 2); debug_event('UI', "truncate called with $max, refusing to do stupid things to $text", 2);
@ -302,8 +317,7 @@ class UI {
$text = iconv_substr($text, 0, $max - 3, $charset); $text = iconv_substr($text, 0, $max - 3, $charset);
$text .= iconv('ISO-8859-1', $charset, '...'); $text .= iconv('ISO-8859-1', $charset, '...');
} }
} } else {
else {
if (strlen($text) > $max) { if (strlen($text) > $max) {
$text = substr($text, 0, $max - 3) . '...'; $text = substr($text, 0, $max - 3) . '...';
} }
@ -318,7 +332,8 @@ class UI {
* Convenience function that, if the output is going to a browser, * Convenience function that, if the output is going to a browser,
* blarfs JS to do a fancy update. Otherwise it just outputs the text. * blarfs JS to do a fancy update. Otherwise it just outputs the text.
*/ */
public static function update_text($field, $value) { public static function update_text($field, $value)
{
if (defined('CLI')) { if (defined('CLI')) {
echo $value . "\n"; echo $value . "\n";
return; return;

View file

@ -30,8 +30,8 @@
* 1090017. * 1090017.
*/ */
class Update { class Update
{
public $key; public $key;
public $value; public $value;
public static $versions; // array containing version information public static $versions; // array containing version information
@ -41,8 +41,9 @@ class Update {
* *
* This should never be called * This should never be called
*/ */
private function __construct() { private function __construct()
// static class {
// static class
} }
/** /**
@ -52,8 +53,8 @@ class Update {
* Because we may not have the update_info table we have to check * Because we may not have the update_info table we have to check
* for its existence first. * for its existence first.
*/ */
public static function get_version() { public static function get_version()
{
/* Make sure that update_info exits */ /* Make sure that update_info exits */
$sql = "SHOW TABLES LIKE 'update_info'"; $sql = "SHOW TABLES LIKE 'update_info'";
$db_results = Dba::read($sql); $db_results = Dba::read($sql);
@ -85,7 +86,8 @@ class Update {
* *
* Make the version number pretty. * Make the version number pretty.
*/ */
public static function format_version($data) { public static function format_version($data)
{
$new_version = $new_version =
substr($data, 0, strlen($data) - 5) . '.' . substr($data, 0, strlen($data) - 5) . '.' .
substr($data, strlen($data) - 5, 1) . ' Build:' . substr($data, strlen($data) - 5, 1) . ' Build:' .
@ -99,7 +101,8 @@ class Update {
* *
* Checks to see if we need to update ampache at all. * Checks to see if we need to update ampache at all.
*/ */
public static function need_update() { public static function need_update()
{
$current_version = self::get_version(); $current_version = self::get_version();
if (!is_array(self::$versions)) { if (!is_array(self::$versions)) {
@ -114,15 +117,15 @@ class Update {
} }
return false; return false;
} }
/** /**
* populate_version * populate_version
* just sets an array the current differences * just sets an array the current differences
* that require an update * that require an update
*/ */
public static function populate_version() { public static function populate_version()
{
/* Define the array */ /* Define the array */
$version = array(); $version = array();
@ -267,7 +270,7 @@ class Update {
$version[] = array('version' => '360006','description' => $update_string); $version[] = array('version' => '360006','description' => $update_string);
$update_string = '- Verify remote_username and remote_password were added correctly to catalog table.<br />'; $update_string = '- Verify remote_username and remote_password were added correctly to catalog table.<br />';
$version[] = array('version' => '360008','description' => $update_string); $version[] = array('version' => '360008','description' => $update_string);
$update_string = '- Allow long sessionids in tmp_playlist table.<br />'; $update_string = '- Allow long sessionids in tmp_playlist table.<br />';
$version[] = array('version' => '360009', 'description' => $update_string); $version[] = array('version' => '360009', 'description' => $update_string);
@ -286,22 +289,22 @@ class Update {
$update_string = '- Increase the length of sessionids again.<br />'; $update_string = '- Increase the length of sessionids again.<br />';
$version[] = array('version' => '360014', 'description' => $update_string); $version[] = array('version' => '360014', 'description' => $update_string);
$update_string = '- Add iframes parameter to preferences.<br />'; $update_string = '- Add iframes parameter to preferences.<br />';
$version[] = array('version' => '360015', 'description' => $update_string); $version[] = array('version' => '360015', 'description' => $update_string);
$update_string = '- Optionally filter Now Playing to return only the last song per user.<br />'; $update_string = '- Optionally filter Now Playing to return only the last song per user.<br />';
$version[] = array('version' => '360016', 'description' => $update_string); $version[] = array('version' => '360016', 'description' => $update_string);
$update_string = '- Add user flags on objects.<br />'; $update_string = '- Add user flags on objects.<br />';
$version[] = array('version' => '360017', 'description' => $update_string); $version[] = array('version' => '360017', 'description' => $update_string);
$update_string = '- Add album default sort value to preferences.<br />'; $update_string = '- Add album default sort value to preferences.<br />';
$version[] = array('version' => '360018', 'description' => $update_string); $version[] = array('version' => '360018', 'description' => $update_string);
$update_string = '- Add option to show number of times a song was played.<br />'; $update_string = '- Add option to show number of times a song was played.<br />';
$version[] = array('version' => '360019', 'description' => $update_string); $version[] = array('version' => '360019', 'description' => $update_string);
$update_string = '- Catalog types are plugins now.<br />'; $update_string = '- Catalog types are plugins now.<br />';
$version[] = array('version' => '360020', 'description' => $update_string); $version[] = array('version' => '360020', 'description' => $update_string);
@ -315,8 +318,8 @@ class Update {
* updates to the database. This will actually * updates to the database. This will actually
* echo out the list... * echo out the list...
*/ */
public static function display_update() { public static function display_update()
{
$current_version = self::get_version(); $current_version = self::get_version();
if (!is_array(self::$versions)) { if (!is_array(self::$versions)) {
self::$versions = self::populate_version(); self::$versions = self::populate_version();
@ -333,8 +336,7 @@ class Update {
echo 'Version: ', self::format_version($update['version']); echo 'Version: ', self::format_version($update['version']);
if (defined('CLI')) { if (defined('CLI')) {
echo "\n", str_replace('<br />', "\n", $update['description']), "\n"; echo "\n", str_replace('<br />', "\n", $update['description']), "\n";
} } else {
else {
echo '</b><br />', $update['description'], "<br /></li>\n"; echo '</b><br />', $update['description'], "<br /></li>\n";
} }
} // if newer } // if newer
@ -347,9 +349,8 @@ class Update {
if (!defined('CLI')) { echo '<p align="center">'; } if (!defined('CLI')) { echo '<p align="center">'; }
echo T_('No updates needed.'); echo T_('No updates needed.');
if (!defined('CLI')) { if (!defined('CLI')) {
echo '[<a href="', Config::get('web_path'), '">Return</a>]</p>'; echo '[<a href="', Config::get('web_path'), '">Return</a>]</p>';
} } else {
else {
echo "\n"; echo "\n";
} }
} }
@ -362,8 +363,8 @@ class Update {
* that need to be run. Checking to make sure * that need to be run. Checking to make sure
* the function exists first. * the function exists first.
*/ */
public static function run_update() { public static function run_update()
{
/* Nuke All Active session before we start the mojo */ /* Nuke All Active session before we start the mojo */
$sql = "TRUNCATE session"; $sql = "TRUNCATE session";
$db_results = Dba::write($sql); $db_results = Dba::write($sql);
@ -401,8 +402,7 @@ class Update {
// If the update fails drop out // If the update fails drop out
if ($success) { if ($success) {
self::set_version('db_version', $version['version']); self::set_version('db_version', $version['version']);
} } else {
else {
Error::display('update'); Error::display('update');
return false; return false;
} }
@ -427,7 +427,8 @@ class Update {
* This updates the 'update_info' which is used by the updater * This updates the 'update_info' which is used by the updater
* and plugins * and plugins
*/ */
private static function set_version($key, $value) { private static function set_version($key, $value)
{
$sql = "UPDATE update_info SET value='$value' WHERE `key`='$key'"; $sql = "UPDATE update_info SET value='$value' WHERE `key`='$key'";
Dba::write($sql); Dba::write($sql);
} }
@ -439,7 +440,8 @@ class Update {
* minor changes to the song table in an attempt to reduce * minor changes to the song table in an attempt to reduce
* the size of each row * the size of each row
*/ */
public static function update_340003() { public static function update_340003()
{
$retval = true; $retval = true;
$sql = "ALTER TABLE `song` CHANGE `mode` `mode` ENUM( 'abr', 'vbr', 'cbr' ) NULL DEFAULT 'cbr'"; $sql = "ALTER TABLE `song` CHANGE `mode` `mode` ENUM( 'abr', 'vbr', 'cbr' ) NULL DEFAULT 'cbr'";
$retval = Dba::write($sql) ? $retval : false; $retval = Dba::write($sql) ? $retval : false;
@ -527,7 +529,8 @@ class Update {
* Update the session.id to varchar(64) to handle * Update the session.id to varchar(64) to handle
* newer configs * newer configs
*/ */
public static function update_340004() { public static function update_340004()
{
$retval = true; $retval = true;
/* Alter the session.id so that it's 64 */ /* Alter the session.id so that it's 64 */
$sql = "ALTER TABLE `session` CHANGE `id` `id` VARCHAR( 64 ) NOT NULL"; $sql = "ALTER TABLE `session` CHANGE `id` `id` VARCHAR( 64 ) NOT NULL";
@ -580,7 +583,8 @@ class Update {
* update_340005 * update_340005
* This update fixes the preferences types * This update fixes the preferences types
*/ */
public static function update_340005() { public static function update_340005()
{
$retval = true; $retval = true;
$sql = "UPDATE `preference` SET `catagory`='playlist' WHERE `name`='random_method'"; $sql = "UPDATE `preference` SET `catagory`='playlist' WHERE `name`='random_method'";
@ -604,7 +608,7 @@ class Update {
$sql = "ALTER TABLE `tmp_playlist_data` ADD `object_type` VARCHAR( 32 ) NULL AFTER `tmp_playlist`"; $sql = "ALTER TABLE `tmp_playlist_data` ADD `object_type` VARCHAR( 32 ) NULL AFTER `tmp_playlist`";
$retval = Dba::write($sql) ? $retval : false; $retval = Dba::write($sql) ? $retval : false;
return $retval; return $retval;
} // update_340005 } // update_340005
/** /**
@ -612,7 +616,8 @@ class Update {
* This just updates the size of the album_data table * This just updates the size of the album_data table
* and removes the random_method config option * and removes the random_method config option
*/ */
public static function update_340006() { public static function update_340006()
{
// No matter what remove that random method preference // No matter what remove that random method preference
Dba::write("DELETE FROM `preference` WHERE `name`='random_method'"); Dba::write("DELETE FROM `preference` WHERE `name`='random_method'");
return true; return true;
@ -623,7 +628,8 @@ class Update {
* This update converts the session.value to a longtext * This update converts the session.value to a longtext
* and adds a session_stream table * and adds a session_stream table
*/ */
public static function update_340007() { public static function update_340007()
{
$retval = true; $retval = true;
// Tweak the session table to handle larger session vars for my page-a-nation hotness // Tweak the session table to handle larger session vars for my page-a-nation hotness
$sql = "ALTER TABLE `session` CHANGE `value` `value` LONGTEXT CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL"; $sql = "ALTER TABLE `session` CHANGE `value` `value` LONGTEXT CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL";
@ -644,7 +650,8 @@ class Update {
* This modifies the playlist table to handle the different types of objects that it needs to be able to * This modifies the playlist table to handle the different types of objects that it needs to be able to
* store, and tweaks how dynamic playlist stuff works * store, and tweaks how dynamic playlist stuff works
*/ */
public static function update_340008() { public static function update_340008()
{
$retval = true; $retval = true;
$sql = "ALTER TABLE `playlist_data` CHANGE `song` `object_id` INT( 11 ) UNSIGNED NULL DEFAULT NULL"; $sql = "ALTER TABLE `playlist_data` CHANGE `song` `object_id` INT( 11 ) UNSIGNED NULL DEFAULT NULL";
$retval = Dba::write($sql) ? $retval : false; $retval = Dba::write($sql) ? $retval : false;
@ -682,7 +689,8 @@ class Update {
* update_340009 * update_340009
* This modifies the song table to handle pos fields * This modifies the song table to handle pos fields
*/ */
public static function update_340009() { public static function update_340009()
{
$retval = true; $retval = true;
$sql = "ALTER TABLE `album` ADD `disk` smallint(5) UNSIGNED DEFAULT NULL"; $sql = "ALTER TABLE `album` ADD `disk` smallint(5) UNSIGNED DEFAULT NULL";
$retval = Dba::write($sql) ? $retval : false; $retval = Dba::write($sql) ? $retval : false;
@ -710,7 +718,8 @@ class Update {
* update_340010 * update_340010
* Bunch of minor tweaks to the preference table * Bunch of minor tweaks to the preference table
*/ */
public static function update_340010() { public static function update_340010()
{
$retval = true; $retval = true;
$sql = "UPDATE `preference` SET `catagory`='options' WHERE `name` LIKE 'localplay_%'"; $sql = "UPDATE `preference` SET `catagory`='options' WHERE `name` LIKE 'localplay_%'";
$retval = Dba::write($sql) ? $retval : false; $retval = Dba::write($sql) ? $retval : false;
@ -735,7 +744,8 @@ class Update {
* This update adds in the democratic stuff, checks for some potentially screwed up indexes * This update adds in the democratic stuff, checks for some potentially screwed up indexes
* and removes the timestamp from the playlist, and adds the field to the catalog for the upload dir * and removes the timestamp from the playlist, and adds the field to the catalog for the upload dir
*/ */
public static function update_340012() { public static function update_340012()
{
$retval = true; $retval = true;
$sql = "ALTER TABLE `catalog` ADD `add_path` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL AFTER `path`"; $sql = "ALTER TABLE `catalog` ADD `add_path` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL AFTER `path`";
$retval = Dba::write($sql) ? $retval : false; $retval = Dba::write($sql) ? $retval : false;
@ -764,7 +774,8 @@ class Update {
* This update removes a whole bunch of preferences that are no longer * This update removes a whole bunch of preferences that are no longer
* being used in any way, and changes the ACL XML-RPC to just RPC * being used in any way, and changes the ACL XML-RPC to just RPC
*/ */
public static function update_340013() { public static function update_340013()
{
$sql = "DELETE FROM `preference` WHERE `name`='localplay_mpd_hostname' OR `name`='localplay_mpd_port' " . $sql = "DELETE FROM `preference` WHERE `name`='localplay_mpd_hostname' OR `name`='localplay_mpd_port' " .
"OR `name`='direct_link' OR `name`='localplay_mpd_password' OR `name`='catalog_echo_count'"; "OR `name`='direct_link' OR `name`='localplay_mpd_password' OR `name`='catalog_echo_count'";
$db_results = Dba::write($sql); $db_results = Dba::write($sql);
@ -787,7 +798,8 @@ class Update {
* at the same time it updates the core session table to handle the * at the same time it updates the core session table to handle the
* additional stuff we're going to ask it to do. * additional stuff we're going to ask it to do.
*/ */
public static function update_340014() { public static function update_340014()
{
$retval = true; $retval = true;
$sql = "DROP TABLE IF EXISTS `session_api`"; $sql = "DROP TABLE IF EXISTS `session_api`";
$retval = Dba::write($sql) ? $retval : false; $retval = Dba::write($sql) ? $retval : false;
@ -811,7 +823,8 @@ class Update {
* who say it doesn't work, unreproduceable. This also adds an index to the * who say it doesn't work, unreproduceable. This also adds an index to the
* album art table to try to make the random album art faster * album art table to try to make the random album art faster
*/ */
public static function update_340015() { public static function update_340015()
{
$retval = true; $retval = true;
$sql = "ALTER TABLE `playlist` DROP `date`"; $sql = "ALTER TABLE `playlist` DROP `date`";
$retval = Dba::write($sql) ? $retval : false; $retval = Dba::write($sql) ? $retval : false;
@ -851,7 +864,8 @@ class Update {
* This adds in the base_playlist to the democratic table... should have * This adds in the base_playlist to the democratic table... should have
* done this in the previous one but I screwed up... sigh. * done this in the previous one but I screwed up... sigh.
*/ */
public static function update_340016() { public static function update_340016()
{
$sql = "ALTER TABLE `democratic` ADD `base_playlist` INT ( 11 ) UNSIGNED NOT NULL AFTER `name`"; $sql = "ALTER TABLE `democratic` ADD `base_playlist` INT ( 11 ) UNSIGNED NOT NULL AFTER `name`";
return Dba::write($sql); return Dba::write($sql);
} }
@ -862,7 +876,8 @@ class Update {
* This finalizes the democratic table. * This finalizes the democratic table.
* And fixes the charset crap. * And fixes the charset crap.
*/ */
public static function update_340017() { public static function update_340017()
{
$retval = true; $retval = true;
$sql = "ALTER TABLE `tmp_playlist` DROP `base_playlist`"; $sql = "ALTER TABLE `tmp_playlist` DROP `base_playlist`";
@ -885,7 +900,8 @@ class Update {
* *
* It also adjusts the prefix fields so that we can use more prefixes, * It also adjusts the prefix fields so that we can use more prefixes,
*/ */
public static function update_350001() { public static function update_350001()
{
$retval = true; $retval = true;
$sql = "ALTER TABLE `tag_map` ADD `tag_id` INT ( 11 ) UNSIGNED NOT NULL AFTER `id`"; $sql = "ALTER TABLE `tag_map` ADD `tag_id` INT ( 11 ) UNSIGNED NOT NULL AFTER `id`";
$retval = Dba::write($sql) ? $retval : false; $retval = Dba::write($sql) ? $retval : false;
@ -913,7 +929,8 @@ class Update {
* we split them out into one serialized array per row, per person. A little * we split them out into one serialized array per row, per person. A little
* slow this way when browsing, but faster and more flexible when not. * slow this way when browsing, but faster and more flexible when not.
*/ */
public static function update_350002() { public static function update_350002()
{
$retval = true; $retval = true;
$sql = "ALTER TABLE `song` DROP `genre`"; $sql = "ALTER TABLE `song` DROP `genre`";
@ -936,7 +953,8 @@ class Update {
* simplify things for the first little bit and then if it all works out * simplify things for the first little bit and then if it all works out
* we will worry about making it complex again. One thing at a time people... * we will worry about making it complex again. One thing at a time people...
*/ */
public static function update_350003() { public static function update_350003()
{
$retval = true; $retval = true;
$sql = "ALTER TABLE `tag` DROP `order`"; $sql = "ALTER TABLE `tag` DROP `order`";
@ -961,7 +979,8 @@ class Update {
* This update makes some changes to the ACL table so that it can support * This update makes some changes to the ACL table so that it can support
* IPv6 entries as well as some other feature enhancements. * IPv6 entries as well as some other feature enhancements.
*/ */
public static function update_350004() { public static function update_350004()
{
$retval = true; $retval = true;
$sql = "ALTER TABLE `session` CHANGE `ip` `ip` VARBINARY( 255 ) NULL"; $sql = "ALTER TABLE `session` CHANGE `ip` `ip` VARBINARY( 255 ) NULL";
@ -1064,7 +1083,8 @@ class Update {
* *
* This update adds the video table... *gasp* no you didn't <head shake> * This update adds the video table... *gasp* no you didn't <head shake>
*/ */
public static function update_350005() { public static function update_350005()
{
$retval = true; $retval = true;
$sql = " CREATE TABLE `video` (" . $sql = " CREATE TABLE `video` (" .
@ -1103,7 +1123,8 @@ class Update {
* *
* This update inserts the Lyrics pref table... * This update inserts the Lyrics pref table...
*/ */
public static function update_350006() { public static function update_350006()
{
$sql = "INSERT INTO `preference` VALUES (69,'show_lyrics','0','Show Lyrics',0,'boolean','interface')"; $sql = "INSERT INTO `preference` VALUES (69,'show_lyrics','0','Show Lyrics',0,'boolean','interface')";
Dba::write($sql); Dba::write($sql);
@ -1119,7 +1140,8 @@ class Update {
* This update adds in the random rules tables. Also increase the size of the * This update adds in the random rules tables. Also increase the size of the
* blobs on the album and artist data and add track to tmp_playlist_data * blobs on the album and artist data and add track to tmp_playlist_data
*/ */
public static function update_350007() { public static function update_350007()
{
$retval = true; $retval = true;
// We need to clear the thumbs as they will need to be re-generated // We need to clear the thumbs as they will need to be re-generated
@ -1179,7 +1201,8 @@ class Update {
* Add type to the now playing table so that we can handle different playing * Add type to the now playing table so that we can handle different playing
* information. * information.
*/ */
public static function update_350008() { public static function update_350008()
{
$retval = true; $retval = true;
$sql = "ALTER TABLE `now_playing` CHANGE `song_id` `object_id` INT( 11 ) UNSIGNED NOT NULL"; $sql = "ALTER TABLE `now_playing` CHANGE `song_id` `object_id` INT( 11 ) UNSIGNED NOT NULL";
$retval = Dba::write($sql) ? $retval : false; $retval = Dba::write($sql) ? $retval : false;
@ -1206,7 +1229,7 @@ class Update {
$retval = Dba::write($sql) ? $retval : false; $retval = Dba::write($sql) ? $retval : false;
return $retval; return $retval;
} }
/** /**
* update_360001 * update_360001
@ -1214,7 +1237,8 @@ class Update {
* This adds the MB UUIDs to the different tables as well as some additional * This adds the MB UUIDs to the different tables as well as some additional
* cleanup. * cleanup.
*/ */
public static function update_360001() { public static function update_360001()
{
$retval = true; $retval = true;
$sql = "ALTER TABLE `album` ADD `mbid` CHAR ( 36 ) AFTER `prefix`"; $sql = "ALTER TABLE `album` ADD `mbid` CHAR ( 36 ) AFTER `prefix`";
@ -1242,7 +1266,8 @@ class Update {
* This update makes changes to the cataloging to accomodate the new method * This update makes changes to the cataloging to accomodate the new method
* for syncing between Ampache instances. * for syncing between Ampache instances.
*/ */
public static function update_360002() { public static function update_360002()
{
$retval = true; $retval = true;
// Drop the key from catalog and ACL // Drop the key from catalog and ACL
$sql = "ALTER TABLE `catalog` DROP `key`"; $sql = "ALTER TABLE `catalog` DROP `key`";
@ -1297,7 +1322,8 @@ class Update {
* *
* This update moves the image data to its own table. * This update moves the image data to its own table.
*/ */
public static function update_360003() { public static function update_360003()
{
$sql = "CREATE TABLE `image` (" . $sql = "CREATE TABLE `image` (" .
"`id` int(11) unsigned NOT NULL auto_increment," . "`id` int(11) unsigned NOT NULL auto_increment," .
"`image` mediumblob NOT NULL," . "`image` mediumblob NOT NULL," .
@ -1317,12 +1343,12 @@ class Update {
"_data` WHERE `art` IS NOT NULL"; "_data` WHERE `art` IS NOT NULL";
$db_results = Dba::read($sql); $db_results = Dba::read($sql);
while ($row = Dba::fetch_assoc($db_results)) { while ($row = Dba::fetch_assoc($db_results)) {
$sql = "INSERT INTO `image` " . $sql = "INSERT INTO `image` " .
"(`image`, `mime`, `size`, " . "(`image`, `mime`, `size`, " .
"`object_type`, `object_id`) " . "`object_type`, `object_id`) " .
"VALUES('" . Dba::escape($row['art']) . "VALUES('" . Dba::escape($row['art']) .
"', '" . $row['art_mime'] . "', '" . $row['art_mime'] .
"', 'original', '" . $type . "', '" . "', 'original', '" . $type . "', '" .
$row['object_id'] . "')"; $row['object_id'] . "')";
$db_other_results = Dba::write($sql); $db_other_results = Dba::write($sql);
} }
@ -1338,7 +1364,8 @@ class Update {
* *
* This update creates an index on the rating table. * This update creates an index on the rating table.
*/ */
public static function update_360004() { public static function update_360004()
{
$sql = "CREATE UNIQUE INDEX `unique_rating` ON `rating` (`user`, `object_type`, `object_id`)"; $sql = "CREATE UNIQUE INDEX `unique_rating` ON `rating` (`user`, `object_type`, `object_id`)";
return Dba::write($sql); return Dba::write($sql);
} }
@ -1348,7 +1375,8 @@ class Update {
* *
* This changes the tmp_browse table around. * This changes the tmp_browse table around.
*/ */
public static function update_360005() { public static function update_360005()
{
$retval = true; $retval = true;
$sql = "DROP TABLE IF EXISTS `tmp_browse`"; $sql = "DROP TABLE IF EXISTS `tmp_browse`";
@ -1371,7 +1399,8 @@ class Update {
* *
* This adds the table for newsearch/dynamic playlists * This adds the table for newsearch/dynamic playlists
*/ */
public static function update_360006() { public static function update_360006()
{
$sql = "CREATE TABLE `search` ( $sql = "CREATE TABLE `search` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT, `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`user` int(11) NOT NULL, `user` int(11) NOT NULL,
@ -1390,32 +1419,33 @@ class Update {
* Fix bug that caused the remote_username/password fields to not be created. * Fix bug that caused the remote_username/password fields to not be created.
* FIXME: Huh? * FIXME: Huh?
*/ */
public static function update_360008() { public static function update_360008()
{
$retval = true; $retval = true;
$remote_username = false; $remote_username = false;
$remote_password = false; $remote_password = false;
$sql = "DESCRIBE `catalog`"; $sql = "DESCRIBE `catalog`";
$db_results = Dba::read($sql); $db_results = Dba::read($sql);
while ($row = Dba::fetch_assoc($db_results)) { while ($row = Dba::fetch_assoc($db_results)) {
if ($row['Field'] == 'remote_username') { if ($row['Field'] == 'remote_username') {
$remote_username = true; $remote_username = true;
} }
if ($row['Field'] == 'remote_password') { if ($row['Field'] == 'remote_password') {
$remote_password = true; $remote_password = true;
} }
} // end while } // end while
if (!$remote_username) { if (!$remote_username) {
// Add in Username / Password for catalog - to be used for remote catalogs // Add in Username / Password for catalog - to be used for remote catalogs
$sql = "ALTER TABLE `catalog` ADD `remote_username` VARCHAR ( 255 ) AFTER `catalog_type`"; $sql = "ALTER TABLE `catalog` ADD `remote_username` VARCHAR ( 255 ) AFTER `catalog_type`";
$retval = Dba::write($sql) ? $retval : false; $retval = Dba::write($sql) ? $retval : false;
} }
if (!$remote_password) { if (!$remote_password) {
$sql = "ALTER TABLE `catalog` ADD `remote_password` VARCHAR ( 255 ) AFTER `remote_username`"; $sql = "ALTER TABLE `catalog` ADD `remote_password` VARCHAR ( 255 ) AFTER `remote_username`";
$retval = Dba::write($sql) ? $retval : false; $retval = Dba::write($sql) ? $retval : false;
} }
return $retval; return $retval;
} }
@ -1426,7 +1456,8 @@ class Update {
* The main session table was already updated to use varchar(64) for the ID, * The main session table was already updated to use varchar(64) for the ID,
* tmp_playlist needs the same change * tmp_playlist needs the same change
*/ */
public static function update_360009() { public static function update_360009()
{
$sql = "ALTER TABLE `tmp_playlist` CHANGE `session` `session` VARCHAR(64)"; $sql = "ALTER TABLE `tmp_playlist` CHANGE `session` `session` VARCHAR(64)";
return Dba::write($sql); return Dba::write($sql);
} }
@ -1434,10 +1465,11 @@ class Update {
/** /**
* update_360010 * update_360010
* *
* MBz NGS means collaborations have more than one MBID (the ones * MBz NGS means collaborations have more than one MBID (the ones
* belonging to the underlying artists). We need a bigger column. * belonging to the underlying artists). We need a bigger column.
*/ */
public static function update_360010() { public static function update_360010()
{
$sql = 'ALTER TABLE `artist` CHANGE `mbid` `mbid` VARCHAR(1369)'; $sql = 'ALTER TABLE `artist` CHANGE `mbid` `mbid` VARCHAR(1369)';
return Dba::write($sql); return Dba::write($sql);
} }
@ -1448,7 +1480,8 @@ class Update {
* We need a place to store actual playlist data for downloadable * We need a place to store actual playlist data for downloadable
* playlist files. * playlist files.
*/ */
public static function update_360011() { public static function update_360011()
{
$sql = 'CREATE TABLE `stream_playlist` (' . $sql = 'CREATE TABLE `stream_playlist` (' .
'`id` int(11) unsigned NOT NULL AUTO_INCREMENT,' . '`id` int(11) unsigned NOT NULL AUTO_INCREMENT,' .
'`sid` varchar(64) NOT NULL,' . '`sid` varchar(64) NOT NULL,' .
@ -1469,7 +1502,8 @@ class Update {
* *
* Drop the enum on session.type * Drop the enum on session.type
*/ */
public static function update_360012() { public static function update_360012()
{
return Dba::write('ALTER TABLE `session` CHANGE `type` `type` VARCHAR(16) DEFAULT NULL'); return Dba::write('ALTER TABLE `session` CHANGE `type` `type` VARCHAR(16) DEFAULT NULL');
} }
@ -1478,7 +1512,8 @@ class Update {
* *
* MyISAM works better out of the box for the stream_playlist table * MyISAM works better out of the box for the stream_playlist table
*/ */
public static function update_360013() { public static function update_360013()
{
return Dba::write('ALTER TABLE `stream_playlist` ENGINE=MyISAM'); return Dba::write('ALTER TABLE `stream_playlist` ENGINE=MyISAM');
} }
@ -1487,7 +1522,8 @@ class Update {
* *
* PHP session IDs are an ever-growing beast. * PHP session IDs are an ever-growing beast.
*/ */
public static function update_360014() { public static function update_360014()
{
$retval = true; $retval = true;
$retval = Dba::write('ALTER TABLE `stream_playlist` CHANGE `sid` `sid` VARCHAR(256)') ? $retval : false; $retval = Dba::write('ALTER TABLE `stream_playlist` CHANGE `sid` `sid` VARCHAR(256)') ? $retval : false;
@ -1496,17 +1532,18 @@ class Update {
return $retval; return $retval;
} }
/** /**
* update_360015 * update_360015
* *
* This inserts the Iframes preference... * This inserts the Iframes preference...
*/ */
public static function update_360015() { public static function update_360015()
{
$sql = "INSERT INTO `preference` (`name`,`value`,`description`,`level`,`type`,`catagory`) " . $sql = "INSERT INTO `preference` (`name`,`value`,`description`,`level`,`type`,`catagory`) " .
"VALUES ('iframes','0','Iframes',25,'boolean','interface')"; "VALUES ('iframes','0','Iframes',25,'boolean','interface')";
Dba::write($sql); Dba::write($sql);
$id = Dba::insert_id(); $id = Dba::insert_id();
$sql = "INSERT INTO `user_preference` VALUES (-1,?,'0')"; $sql = "INSERT INTO `user_preference` VALUES (-1,?,'0')";
@ -1520,11 +1557,12 @@ class Update {
* *
* Add Now Playing filtered per user preference option * Add Now Playing filtered per user preference option
*/ */
public static function update_360016() { public static function update_360016()
{
$sql = "INSERT INTO `preference` (`name`,`value`,`description`,`level`,`type`,`catagory`) " . $sql = "INSERT INTO `preference` (`name`,`value`,`description`,`level`,`type`,`catagory`) " .
"VALUES ('now_playing_per_user','0','Now playing filtered per user',50,'boolean','interface')"; "VALUES ('now_playing_per_user','0','Now playing filtered per user',50,'boolean','interface')";
Dba::write($sql); Dba::write($sql);
$id = Dba::insert_id(); $id = Dba::insert_id();
$sql = "INSERT INTO `user_preference` VALUES (-1,?,'0')"; $sql = "INSERT INTO `user_preference` VALUES (-1,?,'0')";
@ -1538,7 +1576,8 @@ class Update {
* *
* New table to store user flags. * New table to store user flags.
*/ */
public static function update_360017() { public static function update_360017()
{
$sql = "CREATE TABLE `user_flag` (" . $sql = "CREATE TABLE `user_flag` (" .
"`id` int(11) unsigned NOT NULL AUTO_INCREMENT," . "`id` int(11) unsigned NOT NULL AUTO_INCREMENT," .
"`user` int(11) NOT NULL," . "`user` int(11) NOT NULL," .
@ -1556,11 +1595,12 @@ class Update {
* *
* This inserts the Album default sort preference... * This inserts the Album default sort preference...
*/ */
public static function update_360018() { public static function update_360018()
{
$sql = "INSERT INTO `preference` (`name`,`value`,`description`,`level`,`type`,`catagory`) " . $sql = "INSERT INTO `preference` (`name`,`value`,`description`,`level`,`type`,`catagory`) " .
"VALUES ('album_sort','0','Album Default Sort',25,'string','interface')"; "VALUES ('album_sort','0','Album Default Sort',25,'string','interface')";
Dba::write($sql); Dba::write($sql);
$id = Dba::insert_id(); $id = Dba::insert_id();
$sql = "INSERT INTO `user_preference` VALUES (-1,?,'0')"; $sql = "INSERT INTO `user_preference` VALUES (-1,?,'0')";
@ -1568,17 +1608,18 @@ class Update {
return true; return true;
} }
/** /**
* update_360019 * update_360019
* *
* Add Show number of times a song was played preference * Add Show number of times a song was played preference
*/ */
public static function update_360019() { public static function update_360019()
{
$sql = "INSERT INTO `preference` (`name`,`value`,`description`,`level`,`type`,`catagory`) " . $sql = "INSERT INTO `preference` (`name`,`value`,`description`,`level`,`type`,`catagory`) " .
"VALUES ('show_played_times','0','Show # played',25,'string','interface')"; "VALUES ('show_played_times','0','Show # played',25,'string','interface')";
Dba::write($sql); Dba::write($sql);
$id = Dba::insert_id(); $id = Dba::insert_id();
$sql = "INSERT INTO `user_preference` VALUES (-1,?,'0')"; $sql = "INSERT INTO `user_preference` VALUES (-1,?,'0')";
@ -1586,13 +1627,14 @@ class Update {
return true; return true;
} }
/** /**
* update_360020 * update_360020
* *
* Catalog types are plugins now * Catalog types are plugins now
*/ */
public static function update_360020() { public static function update_360020()
{
$sql = "SELECT `id`, `catalog_type`, `path`, `remote_username`, `remote_password` FROM `catalog`"; $sql = "SELECT `id`, `catalog_type`, `path`, `remote_username`, `remote_password` FROM `catalog`";
$db_results = Dba::read($sql); $db_results = Dba::read($sql);
@ -1600,7 +1642,7 @@ class Update {
$c->install(); $c->install();
$c = Catalog::create_catalog_type('remote'); $c = Catalog::create_catalog_type('remote');
$c->install(); $c->install();
while ($results = Dba::fetch_assoc($db_results)) { while ($results = Dba::fetch_assoc($db_results)) {
if ($results['catalog_type'] == 'local') { if ($results['catalog_type'] == 'local') {
$sql = "INSERT INTO `catalog_local` (`path`, `catalog_id`) VALUES (?, ?)"; $sql = "INSERT INTO `catalog_local` (`path`, `catalog_id`) VALUES (?, ?)";
@ -1610,23 +1652,22 @@ class Update {
Dba::write($sql, array($results['path'], $results['remote_username'], $results['remote_password'], $results['id'])); Dba::write($sql, array($results['path'], $results['remote_username'], $results['remote_password'], $results['id']));
} }
} }
$sql = "ALTER TABLE `catalog` DROP `path`, DROP `remote_username`, DROP `remote_password`"; $sql = "ALTER TABLE `catalog` DROP `path`, DROP `remote_username`, DROP `remote_password`";
$retval = Dba::write($sql); $retval = Dba::write($sql);
$sql = "ALTER TABLE `catalog` MODIFY COLUMN `catalog_type` varchar(128)"; $sql = "ALTER TABLE `catalog` MODIFY COLUMN `catalog_type` varchar(128)";
$retval = Dba::write($sql); $retval = Dba::write($sql);
$sql = "UPDATE `artist` SET `mbid` = null WHERE `mbid` = ''"; $sql = "UPDATE `artist` SET `mbid` = null WHERE `mbid` = ''";
Dba::write($sql); Dba::write($sql);
$sql = "UPDATE `album` SET `mbid` = null WHERE `mbid` = ''"; $sql = "UPDATE `album` SET `mbid` = null WHERE `mbid` = ''";
Dba::write($sql); Dba::write($sql);
$sql = "UPDATE `song` SET `mbid` = null WHERE `mbid` = ''"; $sql = "UPDATE `song` SET `mbid` = null WHERE `mbid` = ''";
Dba::write($sql); Dba::write($sql);
return true; return true;
} }
} }
?>

View file

@ -28,8 +28,8 @@
* with a user_id from user.id * with a user_id from user.id
* *
*/ */
class User extends database_object { class User extends database_object
{
//Basic Componets //Basic Componets
public $id; public $id;
public $username; public $username;
@ -49,8 +49,8 @@ class User extends database_object {
* This function is the constructor object for the user * This function is the constructor object for the user
* class, it currently takes a username * class, it currently takes a username
*/ */
public function __construct($user_id=0) { public function __construct($user_id=0)
{
if (!$user_id) { return false; } if (!$user_id) { return false; }
$this->id = intval($user_id); $this->id = intval($user_id);
@ -73,7 +73,8 @@ class User extends database_object {
* *
* This returns the number of user accounts that exist. * This returns the number of user accounts that exist.
*/ */
public static function count() { public static function count()
{
$sql = 'SELECT COUNT(`id`) FROM `user`'; $sql = 'SELECT COUNT(`id`) FROM `user`';
$db_results = Dba::read($sql); $db_results = Dba::read($sql);
$data = Dba::fetch_row($db_results); $data = Dba::fetch_row($db_results);
@ -94,8 +95,8 @@ class User extends database_object {
* _get_info * _get_info
* This function returns the information for this object * This function returns the information for this object
*/ */
private function _get_info() { private function _get_info()
{
$id = intval($this->id); $id = intval($this->id);
if (parent::is_cached('user',$id)) { if (parent::is_cached('user',$id)) {
@ -127,8 +128,8 @@ class User extends database_object {
* has a tmp_playlist, creating it if it doesn't, then sets $this->playlist * has a tmp_playlist, creating it if it doesn't, then sets $this->playlist
* as a tmp_playlist object that can be fiddled with later on * as a tmp_playlist object that can be fiddled with later on
*/ */
public function load_playlist() { public function load_playlist()
{
$session_id = session_id(); $session_id = session_id();
$this->playlist = Tmp_Playlist::get_from_session($session_id); $this->playlist = Tmp_Playlist::get_from_session($session_id);
@ -140,8 +141,8 @@ class User extends database_object {
* This returns a built user from a username. This is a * This returns a built user from a username. This is a
* static function so it doesn't require an instance * static function so it doesn't require an instance
*/ */
public static function get_from_username($username) { public static function get_from_username($username)
{
$username = Dba::escape($username); $username = Dba::escape($username);
$sql = "SELECT `id` FROM `user` WHERE `username`='$username'"; $sql = "SELECT `id` FROM `user` WHERE `username`='$username'";
@ -159,8 +160,8 @@ class User extends database_object {
* This returns a built user from a email. This is a * This returns a built user from a email. This is a
* static function so it doesn't require an instance * static function so it doesn't require an instance
*/ */
public static function get_from_email($email) { public static function get_from_email($email)
{
$email = Dba::escape($email); $email = Dba::escape($email);
$sql = "SELECT `id` FROM `user` WHERE `email`='$email'"; $sql = "SELECT `id` FROM `user` WHERE `email`='$email'";
@ -177,8 +178,8 @@ class User extends database_object {
* get_catalogs * get_catalogs
* This returns the catalogs as an array of ids that this user is allowed to access * This returns the catalogs as an array of ids that this user is allowed to access
*/ */
public function get_catalogs() { public function get_catalogs()
{
if (parent::is_cached('user_catalog',$this->id)) { if (parent::is_cached('user_catalog',$this->id)) {
return parent::get_from_cache('user_catalog',$this->id); return parent::get_from_cache('user_catalog',$this->id);
} }
@ -205,8 +206,8 @@ class User extends database_object {
* []['prefs'] = array(array('name','display','value')); * []['prefs'] = array(array('name','display','value'));
* []['admin'] = t/f value if this is an admin only section * []['admin'] = t/f value if this is an admin only section
*/ */
function get_preferences($type = 0, $system = false) { public function get_preferences($type = 0, $system = false)
{
// Fill out the user id // Fill out the user id
$user_id = $system ? Dba::escape(-1) : Dba::escape($this->id); $user_id = $system ? Dba::escape(-1) : Dba::escape($this->id);
@ -243,8 +244,8 @@ class User extends database_object {
* set_preferences * set_preferences
* sets the prefs for this specific user * sets the prefs for this specific user
*/ */
public function set_preferences() { public function set_preferences()
{
$user_id = Dba::escape($this->id); $user_id = Dba::escape($this->id);
$sql = "SELECT preference.name,user_preference.value FROM preference,user_preference WHERE user_preference.user='$user_id' " . $sql = "SELECT preference.name,user_preference.value FROM preference,user_preference WHERE user_preference.user='$user_id' " .
@ -261,8 +262,8 @@ class User extends database_object {
* get_favorites * get_favorites
* returns an array of your $type favorites * returns an array of your $type favorites
*/ */
function get_favorites($type) { public function get_favorites($type)
{
$web_path = Config::get('web_path'); $web_path = Config::get('web_path');
$results = Stats::get_user(Config::get('popular_threshold'),$type,$this->id,1); $results = Stats::get_user(Config::get('popular_threshold'),$type,$this->id,1);
@ -313,8 +314,8 @@ class User extends database_object {
* This returns recommended objects of $type. The recommendations * This returns recommended objects of $type. The recommendations
* are based on voodoo economics,the phase of the moon and my current BAL. * are based on voodoo economics,the phase of the moon and my current BAL.
*/ */
function get_recommendations($type) { public function get_recommendations($type)
{
/* First pull all of your ratings of this type */ /* First pull all of your ratings of this type */
$sql = "SELECT object_id,user_rating FROM ratings " . $sql = "SELECT object_id,user_rating FROM ratings " .
"WHERE object_type='" . Dba::escape($type) . "' AND user='" . Dba::escape($this->id) . "'"; "WHERE object_type='" . Dba::escape($type) . "' AND user='" . Dba::escape($this->id) . "'";
@ -379,8 +380,8 @@ class User extends database_object {
* checks to see if $this user is logged in returns their current IP if they * checks to see if $this user is logged in returns their current IP if they
* are logged in * are logged in
*/ */
public function is_logged_in() { public function is_logged_in()
{
$username = Dba::escape($this->username); $username = Dba::escape($this->username);
$sql = "SELECT `id`,`ip` FROM `session` WHERE `username`='$username'" . $sql = "SELECT `id`,`ip` FROM `session` WHERE `username`='$username'" .
@ -401,8 +402,8 @@ class User extends database_object {
* this function checkes to see if this user has access * this function checkes to see if this user has access
* to the passed action (pass a level requirement) * to the passed action (pass a level requirement)
*/ */
function has_access($needed_level) { public function has_access($needed_level)
{
if (!Config::get('use_auth') || Config::get('demo_mode')) { return true; } if (!Config::get('use_auth') || Config::get('demo_mode')) { return true; }
if ($this->access >= $needed_level) { return true; } if ($this->access >= $needed_level) { return true; }
@ -417,7 +418,8 @@ class User extends database_object {
* calls the mini ones does all the error checking and all that * calls the mini ones does all the error checking and all that
* good stuff * good stuff
*/ */
public function update($data) { public function update($data)
{
if (empty($data['username'])) { if (empty($data['username'])) {
Error::add('username', T_('Error Username Required')); Error::add('username', T_('Error Username Required'));
} }
@ -433,8 +435,7 @@ class User extends database_object {
foreach ($data as $name => $value) { foreach ($data as $name => $value) {
if ($name == 'password1') { if ($name == 'password1') {
$name = 'password'; $name = 'password';
} } else {
else {
$value = scrub_in($value); $value = scrub_in($value);
} }
@ -462,8 +463,8 @@ class User extends database_object {
* update_username * update_username
* updates their username * updates their username
*/ */
public function update_username($new_username) { public function update_username($new_username)
{
$new_username = Dba::escape($new_username); $new_username = Dba::escape($new_username);
$sql = "UPDATE `user` SET `username`='$new_username' WHERE `id`='$this->id'"; $sql = "UPDATE `user` SET `username`='$new_username' WHERE `id`='$this->id'";
$this->username = $new_username; $this->username = $new_username;
@ -477,8 +478,8 @@ class User extends database_object {
* Use this function to update the validation key * Use this function to update the validation key
* NOTE: crap this doesn't have update_item the humanity of it all * NOTE: crap this doesn't have update_item the humanity of it all
*/ */
public function update_validation($new_validation) { public function update_validation($new_validation)
{
$new_validation = Dba::escape($new_validation); $new_validation = Dba::escape($new_validation);
$sql = "UPDATE `user` SET `validation`='$new_validation', `disabled`='1' WHERE `id`='" . Dba::escape($this->id) . "'"; $sql = "UPDATE `user` SET `validation`='$new_validation', `disabled`='1' WHERE `id`='" . Dba::escape($this->id) . "'";
$db_results = Dba::write($sql); $db_results = Dba::write($sql);
@ -492,8 +493,8 @@ class User extends database_object {
* update_fullname * update_fullname
* updates their fullname * updates their fullname
*/ */
public function update_fullname($new_fullname) { public function update_fullname($new_fullname)
{
$new_fullname = Dba::escape($new_fullname); $new_fullname = Dba::escape($new_fullname);
$sql = "UPDATE `user` SET `fullname`='$new_fullname' WHERE `id`='$this->id'"; $sql = "UPDATE `user` SET `fullname`='$new_fullname' WHERE `id`='$this->id'";
$db_results = Dba::write($sql); $db_results = Dba::write($sql);
@ -504,8 +505,8 @@ class User extends database_object {
* update_email * update_email
* updates their email address * updates their email address
*/ */
public function update_email($new_email) { public function update_email($new_email)
{
$new_email = Dba::escape($new_email); $new_email = Dba::escape($new_email);
$sql = "UPDATE `user` SET `email`='$new_email' WHERE `id`='$this->id'"; $sql = "UPDATE `user` SET `email`='$new_email' WHERE `id`='$this->id'";
$db_results = Dba::write($sql); $db_results = Dba::write($sql);
@ -516,8 +517,8 @@ class User extends database_object {
* disable * disable
* This disables the current user * This disables the current user
*/ */
public function disable() { public function disable()
{
// Make sure we aren't disabling the last admin // Make sure we aren't disabling the last admin
$sql = "SELECT `id` FROM `user` WHERE `disabled` = '0' AND `id` != '" . $this->id . "' AND `access`='100'"; $sql = "SELECT `id` FROM `user` WHERE `disabled` = '0' AND `id` != '" . $this->id . "' AND `access`='100'";
$db_results = Dba::read($sql); $db_results = Dba::read($sql);
@ -539,8 +540,8 @@ class User extends database_object {
* enable * enable
* this enables the current user * this enables the current user
*/ */
public function enable() { public function enable()
{
$sql = "UPDATE `user` SET `disabled`='0' WHERE id='" . $this->id . "'"; $sql = "UPDATE `user` SET `disabled`='0' WHERE id='" . $this->id . "'";
$db_results = Dba::write($sql); $db_results = Dba::write($sql);
@ -552,8 +553,8 @@ class User extends database_object {
* update_access * update_access
* updates their access level * updates their access level
*/ */
public function update_access($new_access) { public function update_access($new_access)
{
/* Prevent Only User accounts */ /* Prevent Only User accounts */
if ($new_access < '100') { if ($new_access < '100') {
$sql = "SELECT `id` FROM user WHERE `access`='100' AND `id` != '$this->id'"; $sql = "SELECT `id` FROM user WHERE `access`='100' AND `id` != '$this->id'";
@ -571,8 +572,8 @@ class User extends database_object {
@function update_last_seen @function update_last_seen
@discussion updates the last seen data for this user @discussion updates the last seen data for this user
*/ */
function update_last_seen() { public function update_last_seen()
{
$sql = "UPDATE user SET last_seen='" . time() . "' WHERE `id`='$this->id'"; $sql = "UPDATE user SET last_seen='" . time() . "' WHERE `id`='$this->id'";
$db_results = Dba::write($sql); $db_results = Dba::write($sql);
@ -582,8 +583,8 @@ class User extends database_object {
* update_user_stats * update_user_stats
* updates the playcount mojo for this specific user * updates the playcount mojo for this specific user
*/ */
public function update_stats($song_id) { public function update_stats($song_id)
{
$song_info = new Song($song_id); $song_info = new Song($song_id);
$song_info->format(); $song_info->format();
$user = $this->id; $user = $this->id;
@ -604,7 +605,7 @@ class User extends database_object {
Stats::insert('album',$song_info->album,$user); Stats::insert('album',$song_info->album,$user);
Stats::insert('artist',$song_info->artist,$user); Stats::insert('artist',$song_info->artist,$user);
return true; return true;
} // update_stats } // update_stats
@ -613,13 +614,12 @@ class User extends database_object {
* This inserts a row into the IP History recording this user at this * This inserts a row into the IP History recording this user at this
* address at this time in this place, doing this thing.. you get the point * address at this time in this place, doing this thing.. you get the point
*/ */
public function insert_ip_history() { public function insert_ip_history()
{
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])){ if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$sip = $_SERVER['HTTP_X_FORWARDED_FOR']; $sip = $_SERVER['HTTP_X_FORWARDED_FOR'];
debug_event('User Ip', 'Login from ip adress: ' . $sip,'3'); debug_event('User Ip', 'Login from ip adress: ' . $sip,'3');
} } else {
else {
$sip = $_SERVER['REMOTE_ADDR']; $sip = $_SERVER['REMOTE_ADDR'];
debug_event('User Ip', 'Login from ip adress: ' . $sip,'3'); debug_event('User Ip', 'Login from ip adress: ' . $sip,'3');
} }
@ -647,8 +647,8 @@ class User extends database_object {
* create * create
* inserts a new user into ampache * inserts a new user into ampache
*/ */
public static function create($username, $fullname, $email, $password, $access, $disabled = false) { public static function create($username, $fullname, $email, $password, $access, $disabled = false)
{
/* Lets clean up the fields... */ /* Lets clean up the fields... */
$username = Dba::escape($username); $username = Dba::escape($username);
$fullname = Dba::escape($fullname); $fullname = Dba::escape($fullname);
@ -681,8 +681,8 @@ class User extends database_object {
* update_password * update_password
* updates a users password * updates a users password
*/ */
public function update_password($new_password) { public function update_password($new_password)
{
$new_password = hash('sha256',$new_password); $new_password = hash('sha256',$new_password);
$new_password = Dba::escape($new_password); $new_password = Dba::escape($new_password);
@ -700,15 +700,13 @@ class User extends database_object {
* user for an admin, these should not be normally called when creating a * user for an admin, these should not be normally called when creating a
* user object * user object
*/ */
public function format() { public function format()
{
/* If they have a last seen date */ /* If they have a last seen date */
if (!$this->last_seen) { $this->f_last_seen = T_('Never'); } if (!$this->last_seen) { $this->f_last_seen = T_('Never'); } else { $this->f_last_seen = date("m\/d\/Y - H:i",$this->last_seen); }
else { $this->f_last_seen = date("m\/d\/Y - H:i",$this->last_seen); }
/* If they have a create date */ /* If they have a create date */
if (!$this->create_date) { $this->f_create_date = T_('Unknown'); } if (!$this->create_date) { $this->f_create_date = T_('Unknown'); } else { $this->f_create_date = date("m\/d\/Y - H:i",$this->create_date); }
else { $this->f_create_date = date("m\/d\/Y - H:i",$this->create_date); }
// Base link // Base link
$this->f_link = '<a href="' . Config::get('web_path') . '/stats.php?action=show_user&user_id=' . $this->id . '">' . $this->fullname . '</a>'; $this->f_link = '<a href="' . Config::get('web_path') . '/stats.php?action=show_user&user_id=' . $this->id . '">' . $this->fullname . '</a>';
@ -727,8 +725,7 @@ class User extends database_object {
/* Get Users Last ip */ /* Get Users Last ip */
if (count($data = $this->get_ip_history(1))) { if (count($data = $this->get_ip_history(1))) {
$this->ip_history = inet_ntop($data['0']['ip']); $this->ip_history = inet_ntop($data['0']['ip']);
} } else {
else {
$this->ip_history = T_('Not Enough Data'); $this->ip_history = T_('Not Enough Data');
} }
@ -739,8 +736,8 @@ class User extends database_object {
* takes an array of objects and formats them corrrectly * takes an array of objects and formats them corrrectly
* and returns a simply array with just <a href values * and returns a simply array with just <a href values
*/ */
public function format_favorites($items) { public function format_favorites($items)
{
// The length of the longest item // The length of the longest item
$maxlen = strlen($items[0]->count); $maxlen = strlen($items[0]->count);
@ -767,8 +764,8 @@ class User extends database_object {
* This takes an array of [object_id] = ratings * This takes an array of [object_id] = ratings
* and displays them in a semi-pretty format * and displays them in a semi-pretty format
*/ */
function format_recommendations($items,$type) { function format_recommendations($items,$type)
{
foreach ($items as $object_id=>$rating) { foreach ($items as $object_id=>$rating) {
switch ($type) { switch ($type) {
@ -801,8 +798,8 @@ class User extends database_object {
* access_name_to_level * access_name_to_level
* This takes the access name for the user and returns the level * This takes the access name for the user and returns the level
*/ */
public static function access_name_to_level($level) { public static function access_name_to_level($level)
{
switch ($level) { switch ($level) {
case 'admin': case 'admin':
return '100'; return '100';
@ -832,8 +829,8 @@ class User extends database_object {
* If -1 is passed it also removes duplicates from the `preferences` * If -1 is passed it also removes duplicates from the `preferences`
* table. * table.
*/ */
public static function fix_preferences($user_id) { public static function fix_preferences($user_id)
{
$user_id = Dba::escape($user_id); $user_id = Dba::escape($user_id);
/* Get All Preferences for the current user */ /* Get All Preferences for the current user */
@ -916,8 +913,8 @@ class User extends database_object {
* deletes this user and everything associated with it. This will affect * deletes this user and everything associated with it. This will affect
* ratings and tottal stats * ratings and tottal stats
*/ */
public function delete() { public function delete()
{
/* /*
Before we do anything make sure that they aren't the last Before we do anything make sure that they aren't the last
admin admin
@ -993,8 +990,8 @@ class User extends database_object {
* calcs difference between now and last_seen * calcs difference between now and last_seen
* if less than delay, we consider them still online * if less than delay, we consider them still online
*/ */
public function is_online( $delay = 1200 ) { public function is_online( $delay = 1200 )
{
return time() - $this->last_seen <= $delay; return time() - $this->last_seen <= $delay;
} // is_online } // is_online
@ -1003,8 +1000,8 @@ class User extends database_object {
* get_user_validation * get_user_validation
*if user exists before activation can be done. *if user exists before activation can be done.
*/ */
public static function get_validation($username) { public static function get_validation($username)
{
$usename = Dba::escape($username); $usename = Dba::escape($username);
$sql = "SELECT `validation` FROM `user` WHERE `username`='$username'"; $sql = "SELECT `validation` FROM `user` WHERE `username`='$username'";
@ -1021,8 +1018,8 @@ class User extends database_object {
* This gets the recently played items for this user respecting * This gets the recently played items for this user respecting
* the limit passed * the limit passed
*/ */
public function get_recently_played($limit,$type='') { public function get_recently_played($limit,$type='')
{
if (!$type) { $type = 'song'; } if (!$type) { $type = 'song'; }
$sql = "SELECT * FROM `object_count` WHERE `object_type`='$type' AND `user`='$this->id' " . $sql = "SELECT * FROM `object_count` WHERE `object_type`='$type' AND `user`='$this->id' " .
@ -1042,8 +1039,8 @@ class User extends database_object {
* This returns the ip_history from the * This returns the ip_history from the
* last Config::get('user_ip_cardinality') days * last Config::get('user_ip_cardinality') days
*/ */
public function get_ip_history($count='',$distinct='') { public function get_ip_history($count='',$distinct='')
{
$username = Dba::escape($this->id); $username = Dba::escape($this->id);
$count = $count ? intval($count) : intval(Config::get('user_ip_cardinality')); $count = $count ? intval($count) : intval(Config::get('user_ip_cardinality'));
@ -1073,8 +1070,8 @@ class User extends database_object {
* activate_user * activate_user
* the user from public_registration * the user from public_registration
*/ */
public function activate_user($username) { public function activate_user($username)
{
$username = Dba::escape($username); $username = Dba::escape($username);
$sql = "UPDATE `user` SET `disabled`='0' WHERE `username`='$username'"; $sql = "UPDATE `user` SET `disabled`='0' WHERE `username`='$username'";
@ -1086,8 +1083,8 @@ class User extends database_object {
* is_xmlrpc * is_xmlrpc
* checks to see if this is a valid xmlrpc user * checks to see if this is a valid xmlrpc user
*/ */
public function is_xmlrpc() { public function is_xmlrpc()
{
/* If we aren't using XML-RPC return true */ /* If we aren't using XML-RPC return true */
if (!Config::get('xml_rpc')) { if (!Config::get('xml_rpc')) {
return false; return false;
@ -1105,8 +1102,8 @@ class User extends database_object {
* This checks to make sure the username passed doesn't already * This checks to make sure the username passed doesn't already
* exist in this instance of ampache * exist in this instance of ampache
*/ */
public static function check_username($username) { public static function check_username($username)
{
$username = Dba::escape($username); $username = Dba::escape($username);
$sql = "SELECT `id` FROM `user` WHERE `username`='$username'"; $sql = "SELECT `id` FROM `user` WHERE `username`='$username'";
@ -1124,8 +1121,8 @@ class User extends database_object {
* rebuild_all_preferences * rebuild_all_preferences
* This rebuilds the user preferences for all installed users, called by the plugin functions * This rebuilds the user preferences for all installed users, called by the plugin functions
*/ */
public static function rebuild_all_preferences() { public static function rebuild_all_preferences()
{
$sql = "SELECT * FROM `user`"; $sql = "SELECT * FROM `user`";
$db_results = Dba::read($sql); $db_results = Dba::read($sql);
@ -1140,4 +1137,3 @@ class User extends database_object {
} // rebuild_all_preferences } // rebuild_all_preferences
} //end user class } //end user class
?>

View file

@ -26,35 +26,35 @@
* This user flag/unflag songs, albums and artists. * This user flag/unflag songs, albums and artists.
* *
*/ */
class Userflag extends database_object { class Userflag extends database_object
{
// Public variables // Public variables
public $id; // The ID of the object flagged public $id; // The ID of the object flagged
public $type; // The type of object we want public $type; // The type of object we want
/** /**
* Constructor * Constructor
* This is run every time a new object is created, and requires * This is run every time a new object is created, and requires
* the id and type of object that we need to pull the flag for * the id and type of object that we need to pull the flag for
*/ */
public function __construct($id, $type) { public function __construct($id, $type)
{
$this->id = intval($id); $this->id = intval($id);
$this->type = $type; $this->type = $type;
return true; return true;
} // Constructor } // Constructor
/** /**
* build_cache * build_cache
* This attempts to get everything we'll need for this page load in a * This attempts to get everything we'll need for this page load in a
* single query, saving on connection overhead * single query, saving on connection overhead
*/ */
public static function build_cache($type, $ids, $user_id = null) { public static function build_cache($type, $ids, $user_id = null)
{
if (!is_array($ids) OR !count($ids)) { return false; } if (!is_array($ids) OR !count($ids)) { return false; }
if (is_null($user_id)) { if (is_null($user_id)) {
$user_id = $GLOBALS['user']->id; $user_id = $GLOBALS['user']->id;
} }
@ -74,8 +74,7 @@ class Userflag extends database_object {
foreach ($ids as $id) { foreach ($ids as $id) {
if (!isset($userflags[$id])) { if (!isset($userflags[$id])) {
$userflag = 0; $userflag = 0;
} } else {
else {
$userflag = intval($user_ratings[$id]); $userflag = intval($user_ratings[$id]);
} }
parent::add_to_cache('userflag_' . $type . '_user' . $user_id, $id, $userflag); parent::add_to_cache('userflag_' . $type . '_user' . $user_id, $id, $userflag);
@ -90,23 +89,24 @@ class Userflag extends database_object {
* *
* Remove userflag for items that no longer exist. * Remove userflag for items that no longer exist.
*/ */
public static function gc() { public static function gc()
foreach(array('song', 'album', 'artist', 'video') as $object_type) { {
foreach (array('song', 'album', 'artist', 'video') as $object_type) {
Dba::write("DELETE FROM `user_flag` USING `user_flag` LEFT JOIN `$object_type` ON `$object_type`.`id` = `user_flag`.`object_id` WHERE `object_type` = '$object_type' AND `$object_type`.`id` IS NULL"); Dba::write("DELETE FROM `user_flag` USING `user_flag` LEFT JOIN `$object_type` ON `$object_type`.`id` = `user_flag`.`object_id` WHERE `object_type` = '$object_type' AND `$object_type`.`id` IS NULL");
} }
} }
public function get_flag($user_id = null) { public function get_flag($user_id = null)
{
if (is_null($user_id)) { if (is_null($user_id)) {
$user_id = $GLOBALS['user']->id; $user_id = $GLOBALS['user']->id;
} }
$key = 'userflag_' . $this->type . '_user' . $user_id; $key = 'userflag_' . $this->type . '_user' . $user_id;
if (parent::is_cached($key, $this->id)) { if (parent::is_cached($key, $this->id)) {
return parent::get_from_cache($key, $this->id); return parent::get_from_cache($key, $this->id);
} }
$sql = "SELECT `id` FROM `user_flag` WHERE `user` = ? ". $sql = "SELECT `id` FROM `user_flag` WHERE `user` = ? ".
"AND `object_id` = ? AND `object_type` = ?"; "AND `object_id` = ? AND `object_type` = ?";
$db_results = Dba::read($sql, array($user_id, $this->id, $this->type)); $db_results = Dba::read($sql, array($user_id, $this->id, $this->type));
@ -115,19 +115,19 @@ class Userflag extends database_object {
if ($results = Dba::fetch_assoc($db_results)) { if ($results = Dba::fetch_assoc($db_results)) {
$flagged = true; $flagged = true;
} }
parent::add_to_cache($key, $this->id, $flagged); parent::add_to_cache($key, $this->id, $flagged);
return $flagged; return $flagged;
} }
/** /**
* set_flag * set_flag
* This function sets the user flag for the current object. * This function sets the user flag for the current object.
* If no userid is passed in, we use the currently logged in user. * If no userid is passed in, we use the currently logged in user.
*/ */
public function set_flag($flagged, $user_id = null) { public function set_flag($flagged, $user_id = null)
{
if (is_null($user_id)) { if (is_null($user_id)) {
$user_id = $GLOBALS['user']->id; $user_id = $GLOBALS['user']->id;
} }
@ -141,8 +141,7 @@ class Userflag extends database_object {
"`object_type` = ? AND " . "`object_type` = ? AND " .
"`user` = ?"; "`user` = ?";
$params = array($this->id, $this->type, $user_id); $params = array($this->id, $this->type, $user_id);
} } else {
else {
$sql = "REPLACE INTO `user_flag` " . $sql = "REPLACE INTO `user_flag` " .
"(`object_id`, `object_type`, `user`, `date`) " . "(`object_id`, `object_type`, `user`, `date`) " .
"VALUES (?, ?, ?, ?)"; "VALUES (?, ?, ?, ?)";
@ -155,18 +154,18 @@ class Userflag extends database_object {
return true; return true;
} // set_flag } // set_flag
/** /**
* get_latest * get_latest
* Get the latest user flagged objects * Get the latest user flagged objects
*/ */
public static function get_latest($type, $user_id=null, $count='', $offset='') { public static function get_latest($type, $user_id=null, $count='', $offset='')
{
if (is_null($user_id)) { if (is_null($user_id)) {
$user_id = $GLOBALS['user']->id; $user_id = $GLOBALS['user']->id;
} }
$user_id = intval($user_id); $user_id = intval($user_id);
if (!$count) { if (!$count) {
$count = Config::get('popular_threshold'); $count = Config::get('popular_threshold');
} }
@ -190,7 +189,7 @@ class Userflag extends database_object {
} }
return $results; return $results;
} // get_latest } // get_latest
/** /**
@ -198,8 +197,8 @@ class Userflag extends database_object {
* This takes an id and a type and displays the flag state * This takes an id and a type and displays the flag state
* enabled. * enabled.
*/ */
public static function show($object_id, $type) { public static function show($object_id, $type)
{
// If user flags aren't enabled don't do anything // If user flags aren't enabled don't do anything
if (!Config::get('userflags')) { return false; } if (!Config::get('userflags')) { return false; }
@ -209,4 +208,3 @@ class Userflag extends database_object {
} // show } // show
} //end rating class } //end rating class
?>

View file

@ -26,8 +26,8 @@
* Ampache-friendly way. * Ampache-friendly way.
* *
*/ */
class vainfo { class vainfo
{
public $encoding = ''; public $encoding = '';
public $encoding_id3v1 = ''; public $encoding_id3v1 = '';
public $encoding_id3v2 = ''; public $encoding_id3v2 = '';
@ -53,8 +53,8 @@ class vainfo {
* This function just sets up the class, it doesn't pull the information. * This function just sets up the class, it doesn't pull the information.
* *
*/ */
public function __construct($file, $encoding = null, $encoding_id3v1 = null, $encoding_id3v2 = null, $dir_pattern = '', $file_pattern ='', $islocal = true) { public function __construct($file, $encoding = null, $encoding_id3v1 = null, $encoding_id3v2 = null, $dir_pattern = '', $file_pattern ='', $islocal = true)
{
$this->islocal = $islocal; $this->islocal = $islocal;
$this->filename = $file; $this->filename = $file;
$this->encoding = $encoding ?: Config::get('site_charset'); $this->encoding = $encoding ?: Config::get('site_charset');
@ -64,11 +64,10 @@ class vainfo {
$this->_dir_pattern = $dir_pattern; $this->_dir_pattern = $dir_pattern;
// FIXME: This looks ugly and probably wrong // FIXME: This looks ugly and probably wrong
if(strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') { if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
$this->_pathinfo = str_replace('%3A', ':', urlencode($this->filename)); $this->_pathinfo = str_replace('%3A', ':', urlencode($this->filename));
$this->_pathinfo = pathinfo(str_replace('%5C', '\\', $this->_pathinfo)); $this->_pathinfo = pathinfo(str_replace('%5C', '\\', $this->_pathinfo));
} } else {
else {
$this->_pathinfo = pathinfo(str_replace('%2F', '/', urlencode($this->filename))); $this->_pathinfo = pathinfo(str_replace('%2F', '/', urlencode($this->filename)));
} }
$this->_pathinfo['extension'] = strtolower($this->_pathinfo['extension']); $this->_pathinfo['extension'] = strtolower($this->_pathinfo['extension']);
@ -88,8 +87,7 @@ class vainfo {
// get id3tag encoding (try to work around off-spec id3v1 tags) // get id3tag encoding (try to work around off-spec id3v1 tags)
try { try {
$this->_raw = $this->_getID3->analyze($file); $this->_raw = $this->_getID3->analyze($file);
} } catch (Exception $error) {
catch (Exception $error) {
debug_event('getID3', "Broken file detected: $file: " . $error->message, 1); debug_event('getID3', "Broken file detected: $file: " . $error->message, 1);
$this->_broken = true; $this->_broken = true;
return false; return false;
@ -97,11 +95,9 @@ class vainfo {
if (Config::get('mb_detect_order')) { if (Config::get('mb_detect_order')) {
$mb_order = Config::get('mb_detect_order'); $mb_order = Config::get('mb_detect_order');
} } elseif (function_exists('mb_detect_order')) {
elseif (function_exists('mb_detect_order')) {
$mb_order = implode(", ", mb_detect_order()); $mb_order = implode(", ", mb_detect_order());
} } else {
else {
$mb_order = "auto"; $mb_order = "auto";
} }
@ -109,12 +105,11 @@ class vainfo {
if ($encoding_id3v1) { if ($encoding_id3v1) {
$this->encoding_id3v1 = $encoding_id3v1; $this->encoding_id3v1 = $encoding_id3v1;
} } else {
else {
foreach ($test_tags as $tag) { foreach ($test_tags as $tag) {
if ($value = $this->_raw['id3v1'][$tag]) { if ($value = $this->_raw['id3v1'][$tag]) {
$tags[$tag] = $value; $tags[$tag] = $value;
} }
} }
$this->encoding_id3v1 = self::_detect_encoding($tags, $mb_order); $this->encoding_id3v1 = self::_detect_encoding($tags, $mb_order);
@ -135,8 +130,9 @@ class vainfo {
$this->_getID3->encoding_id3v1 = $this->encoding_id3v1; $this->_getID3->encoding_id3v1 = $this->encoding_id3v1;
} }
} }
public function forceSize($size) { public function forceSize($size)
{
$this->_forcedSize = $size; $this->_forcedSize = $size;
} }
@ -146,7 +142,8 @@ class vainfo {
* Takes an array of tags and attempts to automatically detect their * Takes an array of tags and attempts to automatically detect their
* encoding. * encoding.
*/ */
private static function _detect_encoding($tags, $mb_order) { private static function _detect_encoding($tags, $mb_order)
{
if (function_exists('mb_detect_encoding')) { if (function_exists('mb_detect_encoding')) {
$encodings = array(); $encodings = array();
if (is_array($tags)) { if (is_array($tags)) {
@ -166,8 +163,7 @@ class vainfo {
if ($encoding != 'ASCII' && $encoding != '0') { if ($encoding != 'ASCII' && $encoding != '0') {
return $encoding; return $encoding;
} } else {
else {
return 'ISO-8859-1'; return 'ISO-8859-1';
} }
} }
@ -180,7 +176,8 @@ class vainfo {
* *
* This function runs the various steps to gathering the metadata * This function runs the various steps to gathering the metadata
*/ */
public function get_info() { public function get_info()
{
// If this is broken, don't waste time figuring it out a second // If this is broken, don't waste time figuring it out a second
// time, just return their rotting carcass of a media file. // time, just return their rotting carcass of a media file.
if ($this->_broken) { if ($this->_broken) {
@ -191,8 +188,7 @@ class vainfo {
if ($this->islocal) { if ($this->islocal) {
try { try {
$this->_raw = $this->_getID3->analyze($this->filename); $this->_raw = $this->_getID3->analyze($this->filename);
} } catch (Exception $error) {
catch (Exception $error) {
debug_event('getID2', 'Unable to catalog file: ' . $error->message, 1); debug_event('getID2', 'Unable to catalog file: ' . $error->message, 1);
} }
} }
@ -200,7 +196,7 @@ class vainfo {
/* Figure out what type of file we are dealing with */ /* Figure out what type of file we are dealing with */
$this->type = $this->_get_type(); $this->type = $this->_get_type();
$enabled_sources = (array)Config::get('metadata_order'); $enabled_sources = (array) Config::get('metadata_order');
if (in_array('filename', $enabled_sources)) { if (in_array('filename', $enabled_sources)) {
$this->tags['filename'] = $this->_parse_filename($this->filename); $this->tags['filename'] = $this->_parse_filename($this->filename);
@ -222,11 +218,12 @@ class vainfo {
* tag_order doesn't match anything then it throws up its hands and uses * tag_order doesn't match anything then it throws up its hands and uses
* everything in random order. * everything in random order.
*/ */
public static function get_tag_type($results, $config_key = 'metadata_order') { public static function get_tag_type($results, $config_key = 'metadata_order')
$order = (array)Config::get($config_key); {
$order = (array) Config::get($config_key);
// Iterate through the defined key order adding them to an ordered array. // Iterate through the defined key order adding them to an ordered array.
foreach($order as $key) { foreach ($order as $key) {
if ($results[$key]) { if ($results[$key]) {
$returned_keys[] = $key; $returned_keys[] = $key;
} }
@ -255,7 +252,8 @@ class vainfo {
* key we've decided on and the filename and returns it in a * key we've decided on and the filename and returns it in a
* sanitized format that ampache can actually use * sanitized format that ampache can actually use
*/ */
public static function clean_tag_info($results, $keys, $filename = null) { public static function clean_tag_info($results, $keys, $filename = null)
{
$info = array(); $info = array();
$info['file'] = $filename; $info['file'] = $filename;
@ -292,8 +290,7 @@ class vainfo {
if (!is_array($tags['genre'])) { if (!is_array($tags['genre'])) {
// not all tag formats will return an array, but we need one // not all tag formats will return an array, but we need one
$info['genre'][] = trim($tags['genre']); $info['genre'][] = trim($tags['genre']);
} } else {
else {
// if we trim the array we lose everything after 1st entry // if we trim the array we lose everything after 1st entry
foreach ($tags['genre'] as $genre) { foreach ($tags['genre'] as $genre) {
$info['genre'][] = trim($genre); $info['genre'][] = trim($genre);
@ -335,7 +332,8 @@ class vainfo {
* This function takes the raw information and figures out what type of * This function takes the raw information and figures out what type of
* file we are dealing with. * file we are dealing with.
*/ */
private function _get_type() { private function _get_type()
{
// There are a few places that the file type can come from, in the end // There are a few places that the file type can come from, in the end
// we trust the encoding type. // we trust the encoding type.
if ($type = $this->_raw['video']['dataformat']) { if ($type = $this->_raw['video']['dataformat']) {
@ -360,8 +358,8 @@ class vainfo {
* *
* This processes the raw getID3 output and bakes it. * This processes the raw getID3 output and bakes it.
*/ */
private function _get_tags() { private function _get_tags()
{
$results = array(); $results = array();
// The tags can come in many different shapes and colors // The tags can come in many different shapes and colors
@ -436,7 +434,8 @@ class vainfo {
* *
* Get additional metadata from plugins * Get additional metadata from plugins
*/ */
private function _get_plugin_tags() { private function _get_plugin_tags()
{
$tag_order = Config::get('metadata_order'); $tag_order = Config::get('metadata_order');
if (!is_array($tag_order)) { if (!is_array($tag_order)) {
$tag_order = array($tag_order); $tag_order = array($tag_order);
@ -459,7 +458,8 @@ class vainfo {
* Gather and return the general information about a file (vbr/cbr, * Gather and return the general information about a file (vbr/cbr,
* sample rate, channels, etc.) * sample rate, channels, etc.)
*/ */
private function _parse_general($tags) { private function _parse_general($tags)
{
$parsed = array(); $parsed = array();
$parsed['title'] = urldecode($this->_pathinfo['filename']); $parsed['title'] = urldecode($this->_pathinfo['filename']);
@ -486,8 +486,8 @@ class vainfo {
* _clean_type * _clean_type
* This standardizes the type that we are given into a recognized type. * This standardizes the type that we are given into a recognized type.
*/ */
private function _clean_type($type) { private function _clean_type($type)
{
switch ($type) { switch ($type) {
case 'mp3': case 'mp3':
case 'mp2': case 'mp2':
@ -512,14 +512,15 @@ class vainfo {
return $type; return $type;
break; break;
} }
} }
/** /**
* _cleanup_generic * _cleanup_generic
* *
* This does generic cleanup. * This does generic cleanup.
*/ */
private function _cleanup_generic($tags) { private function _cleanup_generic($tags)
{
$parsed = array(); $parsed = array();
foreach ($tags as $tagname => $data) { foreach ($tags as $tagname => $data) {
switch ($tagname) { switch ($tagname) {
@ -541,7 +542,8 @@ class vainfo {
* *
* This is supposed to handle lyrics3. FIXME: does it? * This is supposed to handle lyrics3. FIXME: does it?
*/ */
private function _cleanup_lyrics($tags) { private function _cleanup_lyrics($tags)
{
$parsed = array(); $parsed = array();
foreach ($tags as $tag => $data) { foreach ($tags as $tag => $data) {
@ -549,16 +551,17 @@ class vainfo {
$tag = 'lyrics'; $tag = 'lyrics';
} }
$parsed[$tag] = $data[0]; $parsed[$tag] = $data[0];
} }
return $parsed; return $parsed;
} }
/** /**
* _cleanup_vorbiscomment * _cleanup_vorbiscomment
* *
* Standardises tag names from vorbis. * Standardises tag names from vorbis.
*/ */
private function _cleanup_vorbiscomment($tags) { private function _cleanup_vorbiscomment($tags)
{
$parsed = array(); $parsed = array();
foreach ($tags as $tag => $data) { foreach ($tags as $tag => $data) {
@ -581,7 +584,7 @@ class vainfo {
default: default:
$parsed[$tag] = $data[0]; $parsed[$tag] = $data[0];
break; break;
} }
} }
return $parsed; return $parsed;
@ -592,7 +595,8 @@ class vainfo {
* *
* Doesn't do much. * Doesn't do much.
*/ */
private function _cleanup_id3v1($tags) { private function _cleanup_id3v1($tags)
{
$parsed = array(); $parsed = array();
foreach ($tags as $tag => $data) { foreach ($tags as $tag => $data) {
@ -609,7 +613,8 @@ class vainfo {
* *
* Whee, v2! * Whee, v2!
*/ */
private function _cleanup_id3v2($tags) { private function _cleanup_id3v2($tags)
{
$parsed = array(); $parsed = array();
foreach ($tags as $tag => $data) { foreach ($tags as $tag => $data) {
@ -639,7 +644,7 @@ class vainfo {
// getID3 doesn't do all the parsing we need, so grab the raw data // getID3 doesn't do all the parsing we need, so grab the raw data
$id3v2 = $this->_raw['id3v2']; $id3v2 = $this->_raw['id3v2'];
if(!empty($id3v2['UFID'])) { if (!empty($id3v2['UFID'])) {
// Find the MBID for the track // Find the MBID for the track
foreach ($id3v2['UFID'] as $ufid) { foreach ($id3v2['UFID'] as $ufid) {
if ($ufid['ownerid'] == 'http://musicbrainz.org') { if ($ufid['ownerid'] == 'http://musicbrainz.org') {
@ -677,7 +682,8 @@ class vainfo {
/** /**
* _cleanup_riff * _cleanup_riff
*/ */
private function _cleanup_riff($tags) { private function _cleanup_riff($tags)
{
$parsed = array(); $parsed = array();
foreach ($tags as $tag => $data) { foreach ($tags as $tag => $data) {
@ -697,7 +703,8 @@ class vainfo {
/** /**
* _cleanup_quicktime * _cleanup_quicktime
*/ */
private function _cleanup_quicktime($tags) { private function _cleanup_quicktime($tags)
{
$parsed = array(); $parsed = array();
foreach ($tags as $tag => $data) { foreach ($tags as $tag => $data) {
@ -733,22 +740,21 @@ class vainfo {
* This function uses the file and directory patterns to pull out extra tag * This function uses the file and directory patterns to pull out extra tag
* information. * information.
*/ */
private function _parse_filename($filename) { private function _parse_filename($filename)
{
$origin = $filename; $origin = $filename;
$results = array(); $results = array();
// Correctly detect the slash we need to use here // Correctly detect the slash we need to use here
if (strpos($filename, '/') !== false) { if (strpos($filename, '/') !== false) {
$slash_type = '/'; $slash_type = '/';
} } else {
else {
$slash_type = '\\'; $slash_type = '\\';
} }
// Combine the patterns // Combine the patterns
$pattern = preg_quote($this->_dir_pattern) . $slash_type . preg_quote($this->_file_pattern); $pattern = preg_quote($this->_dir_pattern) . $slash_type . preg_quote($this->_file_pattern);
// Remove first left directories from filename to match pattern // Remove first left directories from filename to match pattern
$cntslash = substr_count($pattern, $slash_type) + 1; $cntslash = substr_count($pattern, $slash_type) + 1;
$filepart = explode($slash_type, $filename); $filepart = explode($slash_type, $filename);
@ -796,8 +802,8 @@ class vainfo {
* *
* @return array Return broken title, album, artist * @return array Return broken title, album, artist
*/ */
public function set_broken() { public function set_broken()
{
/* Pull In the config option */ /* Pull In the config option */
$order = Config::get('tag_order'); $order = Config::get('tag_order');
@ -816,4 +822,3 @@ class vainfo {
} // set_broken } // set_broken
} // end class vainfo } // end class vainfo
?>

View file

@ -20,8 +20,8 @@
* *
*/ */
class Video extends database_object implements media { class Video extends database_object implements media
{
public $id; public $id;
public $title; public $title;
public $enabled; public $enabled;
@ -33,8 +33,8 @@ class Video extends database_object implements media {
* This pulls the shoutbox information from the database and returns * This pulls the shoutbox information from the database and returns
* a constructed object, uses user_shout table * a constructed object, uses user_shout table
*/ */
public function __construct($id) { public function __construct($id)
{
// Load the data from the database // Load the data from the database
$info = $this->get_info($id); $info = $this->get_info($id);
foreach ($info as $key=>$value) { foreach ($info as $key=>$value) {
@ -49,8 +49,8 @@ class Video extends database_object implements media {
* build_cache * build_cache
* Build a cache based on the array of ids passed, saves lots of little queries * Build a cache based on the array of ids passed, saves lots of little queries
*/ */
public static function build_cache($ids=array()) { public static function build_cache($ids=array())
{
if (!is_array($ids) OR !count($ids)) { return false; } if (!is_array($ids) OR !count($ids)) { return false; }
$idlist = '(' . implode(',',$ids) . ')'; $idlist = '(' . implode(',',$ids) . ')';
@ -68,8 +68,8 @@ class Video extends database_object implements media {
* format * format
* This formats a video object so that it is human readable * This formats a video object so that it is human readable
*/ */
public function format() { public function format()
{
$this->f_title = scrub_out($this->title); $this->f_title = scrub_out($this->title);
$this->f_link = scrub_out($this->title); $this->f_link = scrub_out($this->title);
$this->f_codec = $this->video_codec . ' / ' . $this->audio_codec; $this->f_codec = $this->video_codec . ' / ' . $this->audio_codec;
@ -79,8 +79,8 @@ class Video extends database_object implements media {
} // format } // format
public function get_stream_types() { public function get_stream_types()
{
return array('native'); return array('native');
} // native_stream } // native_stream
@ -90,8 +90,8 @@ class Video extends database_object implements media {
* This returns a "PLAY" url for the video in question here, this currently feels a little * This returns a "PLAY" url for the video in question here, this currently feels a little
* like a hack, might need to adjust it in the future * like a hack, might need to adjust it in the future
*/ */
public static function play_url($oid,$sid='',$force_http='') { public static function play_url($oid,$sid='',$force_http='')
{
$video = new Video($oid); $video = new Video($oid);
if (!$video->id) { return false; } if (!$video->id) { return false; }
@ -110,7 +110,8 @@ class Video extends database_object implements media {
* *
* FIXME: Video transcoding is not implemented * FIXME: Video transcoding is not implemented
*/ */
public function get_transcode_settings($target = null) { public function get_transcode_settings($target = null)
{
return false; return false;
} }
@ -119,10 +120,8 @@ class Video extends database_object implements media {
* returns true if the video has been flagged and we shouldn't try to re-read * returns true if the video has been flagged and we shouldn't try to re-read
* the meta data * the meta data
*/ */
public function has_flag() { public function has_flag()
{
} // has_flag } // has_flag
} // end Video class } // end Video class

View file

@ -28,8 +28,8 @@
* are all static calls * are all static calls
* *
*/ */
class XML_Data { class XML_Data
{
// This is added so that we don't pop any webservers // This is added so that we don't pop any webservers
private static $limit = '5000'; private static $limit = '5000';
private static $offset = '0'; private static $offset = '0';
@ -40,8 +40,8 @@ class XML_Data {
* *
* We don't use this, as its really a static class * We don't use this, as its really a static class
*/ */
private function __construct() { private function __construct()
{
// Rien a faire // Rien a faire
} // constructor } // constructor
@ -54,8 +54,8 @@ class XML_Data {
* @param integer $offset (description here...) * @param integer $offset (description here...)
* @return void * @return void
*/ */
public static function set_offset($offset) { public static function set_offset($offset)
{
$offset = intval($offset); $offset = intval($offset);
self::$offset = $offset; self::$offset = $offset;
@ -69,8 +69,8 @@ class XML_Data {
* @param integer $limit (description here...) * @param integer $limit (description here...)
* @return void * @return void
*/ */
public static function set_limit($limit) { public static function set_limit($limit)
{
if (!$limit) { return false; } if (!$limit) { return false; }
$limit = intval($limit); $limit = intval($limit);
@ -86,8 +86,8 @@ class XML_Data {
* @param string $type XML_Data type * @param string $type XML_Data type
* @return void * @return void
*/ */
public static function set_type($type) { public static function set_type($type)
{
if (!in_array($type,array('rss','xspf','itunes'))) { return false; } if (!in_array($type,array('rss','xspf','itunes'))) { return false; }
self::$type = $type; self::$type = $type;
@ -104,8 +104,8 @@ class XML_Data {
* @param string $string Error message * @param string $string Error message
* @return string return error message xml * @return string return error message xml
*/ */
public static function error($code,$string) { public static function error($code,$string)
{
$string = self::_header() . "\t<error code=\"$code\"><![CDATA[$string]]></error>" . self::_footer(); $string = self::_header() . "\t<error code=\"$code\"><![CDATA[$string]]></error>" . self::_footer();
return $string; return $string;
@ -120,8 +120,8 @@ class XML_Data {
* @param string $string xml data * @param string $string xml data
* @return string return xml * @return string return xml
*/ */
public static function single_string($key,$string) { public static function single_string($key,$string)
{
$final = self::_header() . "\t<$key><![CDATA[$string]]></$key>" . self::_footer(); $final = self::_header() . "\t<$key><![CDATA[$string]]></$key>" . self::_footer();
return $final; return $final;
@ -136,8 +136,8 @@ class XML_Data {
* @see _header() * @see _header()
* @return string return xml * @return string return xml
*/ */
public static function header() { public static function header()
{
return self::_header(); return self::_header();
} // header } // header
@ -148,10 +148,10 @@ class XML_Data {
* This returns the footer * This returns the footer
* *
* @see _footer() * @see _footer()
* @return string return xml * @return string return xml
*/ */
public static function footer() { public static function footer()
{
return self::_footer(); return self::_footer();
} // footer } // footer
@ -162,16 +162,16 @@ class XML_Data {
* This returns the formatted 'tags' string for an xml document * This returns the formatted 'tags' string for an xml document
* *
*/ */
private static function tags_string($tags) { private static function tags_string($tags)
{
$string = ''; $string = '';
if (is_array($tags)) { if (is_array($tags)) {
foreach ($tags as $tag_id => $data) { foreach ($tags as $tag_id => $data) {
$tag = new Tag($tag_id); $tag = new Tag($tag_id);
$string .= "\t<tag id=\"" . $tag->id . $string .= "\t<tag id=\"" . $tag->id .
'" count="' . count($data['users']) . '" count="' . count($data['users']) .
'"><![CDATA[' . $tag->name . "]]></tag>\n"; '"><![CDATA[' . $tag->name . "]]></tag>\n";
} }
} }
@ -189,25 +189,24 @@ class XML_Data {
* @param boolean $callback (description here...) * @param boolean $callback (description here...)
* @return string return xml * @return string return xml
*/ */
public static function keyed_array($array,$callback='') { public static function keyed_array($array,$callback='')
{
$string = ''; $string = '';
// Foreach it // Foreach it
foreach ($array as $key=>$value) { foreach ($array as $key=>$value) {
$attribute = ''; $attribute = '';
// See if the key has attributes // See if the key has attributes
if (is_array($value) AND isset($value['<attributes>'])) { if (is_array($value) AND isset($value['<attributes>'])) {
$attribute = ' ' . $value['<attributes>']; $attribute = ' ' . $value['<attributes>'];
$key = $value['value']; $key = $value['value'];
} }
// If it's an array, run again // If it's an array, run again
if (is_array($value)) { if (is_array($value)) {
$value = self::keyed_array($value,1); $value = self::keyed_array($value,1);
$string .= "<$key$attribute>\n$value\n</$key>\n"; $string .= "<$key$attribute>\n$value\n</$key>\n";
} } else {
else {
$string .= "\t<$key$attribute><![CDATA[$value]]></$key>\n"; $string .= "\t<$key$attribute><![CDATA[$value]]></$key>\n";
} }
@ -229,8 +228,8 @@ class XML_Data {
* @param array $tags (description here...) * @param array $tags (description here...)
* @return string return xml * @return string return xml
*/ */
public static function tags($tags) { public static function tags($tags)
{
if (count($tags) > self::$limit OR self::$offset > 0) { if (count($tags) > self::$limit OR self::$offset > 0) {
$tags = array_splice($tags,self::$offset,self::$limit); $tags = array_splice($tags,self::$offset,self::$limit);
} }
@ -266,8 +265,8 @@ class XML_Data {
* @param array $artists (description here...) * @param array $artists (description here...)
* @return string return xml * @return string return xml
*/ */
public static function artists($artists) { public static function artists($artists)
{
if (count($artists) > self::$limit OR self::$offset > 0) { if (count($artists) > self::$limit OR self::$offset > 0) {
$artists = array_splice($artists,self::$offset,self::$limit); $artists = array_splice($artists,self::$offset,self::$limit);
} }
@ -308,8 +307,8 @@ class XML_Data {
* @param array $albums (description here...) * @param array $albums (description here...)
* @return string return xml * @return string return xml
*/ */
public static function albums($albums) { public static function albums($albums)
{
if (count($albums) > self::$limit OR self::$offset > 0) { if (count($albums) > self::$limit OR self::$offset > 0) {
$albums = array_splice($albums,self::$offset,self::$limit); $albums = array_splice($albums,self::$offset,self::$limit);
} }
@ -331,8 +330,7 @@ class XML_Data {
// Do a little check for artist stuff // Do a little check for artist stuff
if ($album->artist_count != 1) { if ($album->artist_count != 1) {
$string .= "\t<artist id=\"0\"><![CDATA[Various]]></artist>\n"; $string .= "\t<artist id=\"0\"><![CDATA[Various]]></artist>\n";
} } else {
else {
$string .= "\t<artist id=\"$album->artist_id\"><![CDATA[$album->artist_name]]></artist>\n"; $string .= "\t<artist id=\"$album->artist_id\"><![CDATA[$album->artist_name]]></artist>\n";
} }
@ -361,8 +359,8 @@ class XML_Data {
* @param array $playlists (description here...) * @param array $playlists (description here...)
* @return string return xml * @return string return xml
*/ */
public static function playlists($playlists) { public static function playlists($playlists)
{
if (count($playlists) > self::$limit OR self::$offset > 0) { if (count($playlists) > self::$limit OR self::$offset > 0) {
$playlists = array_slice($playlists,self::$offset,self::$limit); $playlists = array_slice($playlists,self::$offset,self::$limit);
} }
@ -399,8 +397,8 @@ class XML_Data {
* This returns an xml document from an array of song ids. * This returns an xml document from an array of song ids.
* (Spiffy isn't it!) * (Spiffy isn't it!)
*/ */
public static function songs($songs) { public static function songs($songs)
{
if (count($songs) > self::$limit OR self::$offset > 0) { if (count($songs) > self::$limit OR self::$offset > 0) {
$songs = array_slice($songs, self::$offset, self::$limit); $songs = array_slice($songs, self::$offset, self::$limit);
} }
@ -421,10 +419,10 @@ class XML_Data {
$string .= "<song id=\"$song->id\">\n" . $string .= "<song id=\"$song->id\">\n" .
"\t<title><![CDATA[$song->title]]></title>\n" . "\t<title><![CDATA[$song->title]]></title>\n" .
"\t<artist id=\"" . $song->artist . "\t<artist id=\"" . $song->artist .
'"><![CDATA[' . $song->get_artist_name() . '"><![CDATA[' . $song->get_artist_name() .
"]]></artist>\n" . "]]></artist>\n" .
"\t<album id=\"" . $song->album . "\t<album id=\"" . $song->album .
'"><![CDATA[' . $song->get_album_name(). '"><![CDATA[' . $song->get_album_name().
"]]></album>\n" . "]]></album>\n" .
$tag_string . $tag_string .
@ -459,8 +457,8 @@ class XML_Data {
* @param array $videos (description here...) * @param array $videos (description here...)
* @return string return xml * @return string return xml
*/ */
public static function videos($videos) { public static function videos($videos)
{
if (count($videos) > self::$limit OR self::$offset > 0) { if (count($videos) > self::$limit OR self::$offset > 0) {
$videos = array_slice($videos,self::$offset,self::$limit); $videos = array_slice($videos,self::$offset,self::$limit);
} }
@ -497,8 +495,8 @@ class XML_Data {
* @param array $object_ids Object IDs * @param array $object_ids Object IDs
* @return string return xml * @return string return xml
*/ */
public static function democratic($object_ids=array()) { public static function democratic($object_ids=array())
{
if (!is_array($object_ids)) { $object_ids = array(); } if (!is_array($object_ids)) { $object_ids = array(); }
$democratic = Democratic::get_current_playlist(); $democratic = Democratic::get_current_playlist();
@ -559,8 +557,8 @@ class XML_Data {
* @param string $date publish date * @param string $date publish date
* @return string RSS feed xml * @return string RSS feed xml
*/ */
public static function rss_feed($data,$title,$description,$date) { public static function rss_feed($data,$title,$description,$date)
{
$string = "\t<title>$title</title>\n\t<link>" . Config::get('web_path') . "</link>\n\t" . $string = "\t<title>$title</title>\n\t<link>" . Config::get('web_path') . "</link>\n\t" .
"<pubDate>" . date("r",$date) . "</pubDate>\n"; "<pubDate>" . date("r",$date) . "</pubDate>\n";
@ -584,8 +582,8 @@ class XML_Data {
* *
* @return string Header xml tag. * @return string Header xml tag.
*/ */
private static function _header() { private static function _header()
{
switch (self::$type) { switch (self::$type) {
case 'xspf': case 'xspf':
$header = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" . $header = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" .
@ -632,8 +630,8 @@ class XML_Data {
* *
* @return string Footer xml tag. * @return string Footer xml tag.
*/ */
private static function _footer() { private static function _footer()
{
switch (self::$type) { switch (self::$type) {
case 'itunes': case 'itunes':
$footer = "\t\t</dict>\t\n</dict>\n</plist>\n"; $footer = "\t\t</dict>\t\n</dict>\n</plist>\n";
@ -655,5 +653,3 @@ class XML_Data {
} // _footer } // _footer
} // XML_Data } // XML_Data
?>

View file

@ -20,7 +20,8 @@
* *
*/ */
function check_php() { function check_php()
{
if ( if (
check_php_version() && check_php_version() &&
check_php_hash() && check_php_hash() &&
@ -37,34 +38,41 @@ function check_php() {
return false; return false;
} }
function check_php_version() { function check_php_version()
{
if (floatval(phpversion()) < 5.3) { if (floatval(phpversion()) < 5.3) {
return false; return false;
} }
return true; return true;
} }
function check_php_hash() { function check_php_hash()
{
return function_exists('hash_algos'); return function_exists('hash_algos');
} }
function check_php_hash_algo() { function check_php_hash_algo()
{
return function_exists('hash_algos') ? in_array('sha256', hash_algos()) : false; return function_exists('hash_algos') ? in_array('sha256', hash_algos()) : false;
} }
function check_php_json() { function check_php_json()
{
return function_exists('json_encode'); return function_exists('json_encode');
} }
function check_php_session() { function check_php_session()
{
return function_exists('session_set_save_handler'); return function_exists('session_set_save_handler');
} }
function check_php_pdo() { function check_php_pdo()
{
return class_exists('PDO'); return class_exists('PDO');
} }
function check_php_pdo_mysql() { function check_php_pdo_mysql()
{
return class_exists('PDO') ? in_array('mysql', PDO::getAvailableDrivers()) : false; return class_exists('PDO') ? in_array('mysql', PDO::getAvailableDrivers()) : false;
} }
@ -72,8 +80,8 @@ function check_php_pdo_mysql() {
* check_config_values * check_config_values
* checks to make sure that they have at least set the needed variables * checks to make sure that they have at least set the needed variables
*/ */
function check_config_values($conf) { function check_config_values($conf)
{
if (!$conf['database_hostname']) { if (!$conf['database_hostname']) {
return false; return false;
} }
@ -114,8 +122,8 @@ function check_config_values($conf) {
* recommended range, this doesn't take into account the size of your * recommended range, this doesn't take into account the size of your
* catalog. * catalog.
*/ */
function check_php_memory() { function check_php_memory()
{
$current_memory = ini_get('memory_limit'); $current_memory = ini_get('memory_limit');
$current_memory = substr($current_memory,0,strlen($current_memory)-1); $current_memory = substr($current_memory,0,strlen($current_memory)-1);
@ -132,8 +140,8 @@ function check_php_memory() {
* This checks to make sure that the php timelimit is set to some * This checks to make sure that the php timelimit is set to some
* semi-sane limit, IE greater then 60 seconds * semi-sane limit, IE greater then 60 seconds
*/ */
function check_php_timelimit() { function check_php_timelimit()
{
$current = intval(ini_get('max_execution_time')); $current = intval(ini_get('max_execution_time'));
return ($current >= 60 || $current == 0); return ($current >= 60 || $current == 0);
@ -143,7 +151,8 @@ function check_php_timelimit() {
* check_safe_mode * check_safe_mode
* Checks to make sure we aren't in safe mode * Checks to make sure we aren't in safe mode
*/ */
function check_php_safemode() { function check_php_safemode()
{
if (ini_get('safe_mode')) { if (ini_get('safe_mode')) {
return false; return false;
} }
@ -154,7 +163,8 @@ function check_php_safemode() {
* check_override_memory * check_override_memory
* This checks to see if we can manually override the memory limit * This checks to see if we can manually override the memory limit
*/ */
function check_override_memory() { function check_override_memory()
{
/* Check memory */ /* Check memory */
$current_memory = ini_get('memory_limit'); $current_memory = ini_get('memory_limit');
$current_memory = substr($current_memory,0,strlen($current_memory)-1); $current_memory = substr($current_memory,0,strlen($current_memory)-1);
@ -179,7 +189,8 @@ function check_override_memory() {
* check_override_exec_time * check_override_exec_time
* This checks to see if we can manually override the max execution time * This checks to see if we can manually override the max execution time
*/ */
function check_override_exec_time() { function check_override_exec_time()
{
$current = ini_get('max_execution_time'); $current = ini_get('max_execution_time');
set_time_limit($current+60); set_time_limit($current+60);
@ -194,10 +205,10 @@ function check_override_exec_time() {
* check_config_writable * check_config_writable
* This checks whether we can write the config file * This checks whether we can write the config file
*/ */
function check_config_writable() { function check_config_writable()
{
// file eixsts && is writable, or dir is writable // file eixsts && is writable, or dir is writable
return ((file_exists(Config::get('prefix') . '/config/ampache.cfg.php') && is_writable(Config::get('prefix') . '/config/ampache.cfg.php')) return ((file_exists(Config::get('prefix') . '/config/ampache.cfg.php') && is_writable(Config::get('prefix') . '/config/ampache.cfg.php'))
|| (!file_exists(Config::get('prefix') . '/config/ampache.cfg.php') && is_writeable(Config::get('prefix') . '/config/'))); || (!file_exists(Config::get('prefix') . '/config/ampache.cfg.php') && is_writeable(Config::get('prefix') . '/config/')));
} }
@ -206,7 +217,8 @@ function check_config_writable() {
* *
* Convenience function to format the output. * Convenience function to format the output.
*/ */
function debug_result($status = false, $value = null, $comment = '') { function debug_result($status = false, $value = null, $comment = '')
{
$class = $status ? 'ok' : 'notok'; $class = $status ? 'ok' : 'notok';
if (!$value) { if (!$value) {
@ -216,4 +228,3 @@ function debug_result($status = false, $value = null, $comment = '') {
return '[ <span class="' . $class . '">' . scrub_out($value) . return '[ <span class="' . $class . '">' . scrub_out($value) .
'</span> <em>' . $comment . '</em> ]'; '</span> <em>' . $comment . '</em> ]';
} }
?>

View file

@ -25,8 +25,8 @@
* This function attempts to change the php memory limit using init_set. * This function attempts to change the php memory limit using init_set.
* Will never reduce it below the current setting. * Will never reduce it below the current setting.
*/ */
function set_memory_limit($new_limit) { function set_memory_limit($new_limit)
{
$current_limit = ini_get('memory_limit'); $current_limit = ini_get('memory_limit');
if ($current_limit == -1) { if ($current_limit == -1) {
return; return;
@ -45,8 +45,8 @@ function set_memory_limit($new_limit) {
* generate_password * generate_password
* This generates a random password of the specified length * This generates a random password of the specified length
*/ */
function generate_password($length) { function generate_password($length)
{
$vowels = 'aAeEuUyY12345'; $vowels = 'aAeEuUyY12345';
$consonants = 'bBdDgGhHjJmMnNpPqQrRsStTvVwWxXzZ6789'; $consonants = 'bBdDgGhHjJmMnNpPqQrRsStTvVwWxXzZ6789';
$password = ''; $password = '';
@ -57,8 +57,7 @@ function generate_password($length) {
if ($alt == 1) { if ($alt == 1) {
$password .= $consonants[(rand(0,strlen($consonants)-1))]; $password .= $consonants[(rand(0,strlen($consonants)-1))];
$alt = 0; $alt = 0;
} } else {
else {
$password .= $vowels[(rand(0,strlen($vowels)-1))]; $password .= $vowels[(rand(0,strlen($vowels)-1))];
$alt = 1; $alt = 1;
} }
@ -72,14 +71,13 @@ function generate_password($length) {
* scrub_in * scrub_in
* Run on inputs, stuff that might get stuck in our db * Run on inputs, stuff that might get stuck in our db
*/ */
function scrub_in($input) { function scrub_in($input)
{
if (!is_array($input)) { if (!is_array($input)) {
return stripslashes(htmlspecialchars(strip_tags($input), ENT_QUOTES, Config::get('site_charset'))); return stripslashes(htmlspecialchars(strip_tags($input), ENT_QUOTES, Config::get('site_charset')));
} } else {
else {
$results = array(); $results = array();
foreach($input as $item) { foreach ($input as $item) {
$results[] = scrub_in($item); $results[] = scrub_in($item);
} }
return $results; return $results;
@ -91,8 +89,8 @@ function scrub_in($input) {
* This function is used to escape user data that is getting redisplayed * This function is used to escape user data that is getting redisplayed
* onto the page, it htmlentities the mojo * onto the page, it htmlentities the mojo
*/ */
function scrub_out($string) { function scrub_out($string)
{
return htmlentities($string, ENT_QUOTES, Config::get('site_charset')); return htmlentities($string, ENT_QUOTES, Config::get('site_charset'));
} // scrub_out } // scrub_out
@ -101,8 +99,8 @@ function scrub_out($string) {
* unhtmlentities * unhtmlentities
* Undoes htmlentities() * Undoes htmlentities()
*/ */
function unhtmlentities($string) { function unhtmlentities($string)
{
return html_entity_decode($string, ENT_QUOTES, Config::get('site_charset')); return html_entity_decode($string, ENT_QUOTES, Config::get('site_charset'));
} //unhtmlentities } //unhtmlentities
@ -126,13 +124,13 @@ function scrub_arg($arg)
* This takes a value and returns what we consider to be the correct boolean * This takes a value and returns what we consider to be the correct boolean
* value. We need a special function because PHP considers "false" to be true. * value. We need a special function because PHP considers "false" to be true.
*/ */
function make_bool($string) { function make_bool($string)
{
if (strcasecmp($string,'false') == 0) { if (strcasecmp($string,'false') == 0) {
return false; return false;
} }
return (bool)$string; return (bool) $string;
} // make_bool } // make_bool
@ -140,8 +138,8 @@ function make_bool($string) {
* invert_bool * invert_bool
* This returns the opposite of what you've got * This returns the opposite of what you've got
*/ */
function invert_bool($value) { function invert_bool($value)
{
return make_bool($value) ? false : true; return make_bool($value) ? false : true;
} // invert_bool } // invert_bool
@ -153,8 +151,8 @@ function invert_bool($value) {
* is drop one in and it will show up on the context menu. It returns * is drop one in and it will show up on the context menu. It returns
* in the form of an array of names * in the form of an array of names
*/ */
function get_languages() { function get_languages()
{
/* Open the locale directory */ /* Open the locale directory */
$handle = @opendir(Config::get('prefix') . '/locale'); $handle = @opendir(Config::get('prefix') . '/locale');
@ -174,7 +172,7 @@ function get_languages() {
/* Check to see if it's a directory */ /* Check to see if it's a directory */
if (is_dir($full_file) AND substr($file,0,1) != '.' AND $file != 'base') { if (is_dir($full_file) AND substr($file,0,1) != '.' AND $file != 'base') {
switch($file) { switch ($file) {
case 'af_ZA'; $name = 'Afrikaans'; break; /* Afrikaans */ case 'af_ZA'; $name = 'Afrikaans'; break; /* Afrikaans */
case 'ca_ES'; $name = 'Catal&#224;'; break; /* Catalan */ case 'ca_ES'; $name = 'Catal&#224;'; break; /* Catalan */
case 'cs_CZ'; $name = '&#x010c;esky'; break; /* Czech */ case 'cs_CZ'; $name = '&#x010c;esky'; break; /* Czech */
@ -237,7 +235,8 @@ function get_languages() {
* is_rtl * is_rtl
* This checks whether to be a rtl language. * This checks whether to be a rtl language.
*/ */
function is_rtl($locale) { function is_rtl($locale)
{
return in_array($locale, array("he_IL", "fa_IR", "ar_SA")); return in_array($locale, array("he_IL", "fa_IR", "ar_SA"));
} }
@ -247,8 +246,8 @@ function is_rtl($locale) {
* 'tag' name that said pattern code corrasponds to. It returns false if nothing * 'tag' name that said pattern code corrasponds to. It returns false if nothing
* is found. * is found.
*/ */
function translate_pattern_code($code) { function translate_pattern_code($code)
{
$code_array = array('%A'=>'album', $code_array = array('%A'=>'album',
'%a'=>'artist', '%a'=>'artist',
'%c'=>'comment', '%c'=>'comment',
@ -272,7 +271,8 @@ function translate_pattern_code($code) {
* This takes an array of results and re-generates the config file * This takes an array of results and re-generates the config file
* this is used by the installer and by the admin/system page * this is used by the installer and by the admin/system page
*/ */
function generate_config($current) { function generate_config($current)
{
// Start building the new config file // Start building the new config file
$distfile = Config::get('prefix') . '/config/ampache.cfg.php.dist'; $distfile = Config::get('prefix') . '/config/ampache.cfg.php.dist';
$handle = fopen($distfile,'r'); $handle = fopen($distfile,'r');
@ -281,9 +281,9 @@ function generate_config($current) {
$data = explode("\n",$dist); $data = explode("\n",$dist);
foreach ($data as $line) { foreach ($data as $line) {
if (preg_match("/^;?([\w\d]+)\s+=\s+[\"]{1}(.*?)[\"]{1}$/",$line,$matches) if (preg_match("/^;?([\w\d]+)\s+=\s+[\"]{1}(.*?)[\"]{1}$/",$line,$matches)
|| preg_match("/^;?([\w\d]+)\s+=\s+[\']{1}(.*?)[\']{1}$/", $line, $matches) || preg_match("/^;?([\w\d]+)\s+=\s+[\']{1}(.*?)[\']{1}$/", $line, $matches)
|| preg_match("/^;?([\w\d]+)\s+=\s+[\'\"]{0}(.*)[\'\"]{0}$/",$line,$matches)) { || preg_match("/^;?([\w\d]+)\s+=\s+[\'\"]{0}(.*)[\'\"]{0}$/",$line,$matches)) {
$key = $matches[1]; $key = $matches[1];
@ -292,27 +292,25 @@ function generate_config($current) {
// Put in the current value // Put in the current value
if ($key == 'config_version') { if ($key == 'config_version') {
$line = $key . ' = ' . escape_ini($value); $line = $key . ' = ' . escape_ini($value);
} } elseif (isset($current[$key])) {
elseif (isset($current[$key])) {
$line = $key . ' = "' . escape_ini($current[$key]) . '"'; $line = $key . ' = "' . escape_ini($current[$key]) . '"';
unset($current[$key]); unset($current[$key]);
} }
} }
$final .= $line . "\n"; $final .= $line . "\n";
} }
return $final; return $final;
} }
/** /**
* escape_ini * escape_ini
* *
* Escape a value used for inserting into an ini file. * Escape a value used for inserting into an ini file.
* Won't quote ', like addslashes does. * Won't quote ', like addslashes does.
*/ */
function escape_ini($str) { function escape_ini($str)
{
return str_replace('"', '\"', $str); return str_replace('"', '\"', $str);
} }
?>

View file

@ -26,7 +26,8 @@
* *
* @return void * @return void
*/ */
function load_gettext() { function load_gettext()
{
$lang = Config::get('lang'); $lang = Config::get('lang');
$charset = Config::get('site_charset') ?: 'UTF-8'; $charset = Config::get('site_charset') ?: 'UTF-8';
$locale = $lang . '.' . $charset; $locale = $lang . '.' . $charset;
@ -45,8 +46,7 @@ function load_gettext() {
* @param string $string * @param string $string
* @return string * @return string
*/ */
function gettext_noop($string) { function gettext_noop($string)
{
return $string; return $string;
} }
?>

View file

@ -45,18 +45,16 @@ Config::set('prefix', $prefix);
spl_autoload_register(array('Core', 'autoload'), true, true); spl_autoload_register(array('Core', 'autoload'), true, true);
// Check to see if this is http or https // Check to see if this is http or https
if ((isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' ) if ((isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' )
|| (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on')) { || (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on')) {
$http_type = 'https://'; $http_type = 'https://';
} } else {
else {
$http_type = 'http://'; $http_type = 'http://';
} }
if (isset($_SERVER['HTTP_X_FORWARDED_PORT'])) { if (isset($_SERVER['HTTP_X_FORWARDED_PORT'])) {
$http_port = $_SERVER['HTTP_X_FORWARDED_PORT']; $http_port = $_SERVER['HTTP_X_FORWARDED_PORT'];
} } else if (isset($_SERVER['SERVER_PORT'])) {
else if (isset($_SERVER['SERVER_PORT'])) {
$http_port = $_SERVER['SERVER_PORT']; $http_port = $_SERVER['SERVER_PORT'];
} }
if (!isset($http_port) || !$http_port) { if (!isset($http_port) || !$http_port) {
@ -86,4 +84,3 @@ UI::flip_class(array('odd', 'even'));
// Merge GET then POST into REQUEST effectively stripping COOKIE without // Merge GET then POST into REQUEST effectively stripping COOKIE without
// depending on a PHP setting change for the effect // depending on a PHP setting change for the effect
$_REQUEST = array_merge($_GET, $_POST); $_REQUEST = array_merge($_GET, $_POST);
?>

View file

@ -37,12 +37,11 @@ Session::_auto_init();
$path = preg_replace('#(.*)/(\w+\.php)$#', '$1', $_SERVER['PHP_SELF']); $path = preg_replace('#(.*)/(\w+\.php)$#', '$1', $_SERVER['PHP_SELF']);
$path = $http_type . $_SERVER['HTTP_HOST'] . $path; $path = $http_type . $_SERVER['HTTP_HOST'] . $path;
// Check to make sure the config file exists. If it doesn't then go ahead and // Check to make sure the config file exists. If it doesn't then go ahead and
// send them over to the install script. // send them over to the install script.
if (!file_exists($configfile)) { if (!file_exists($configfile)) {
$link = $path . '/install.php'; $link = $path . '/install.php';
} } else {
else {
// Make sure the config file is set up and parsable // Make sure the config file is set up and parsable
$results = @parse_ini_file($configfile); $results = @parse_ini_file($configfile);
@ -121,7 +120,7 @@ if (substr($post_size,strlen($post_size)-1,strlen($post_size)) != 'M') {
// In case the local setting is 0 // In case the local setting is 0
ini_set('session.gc_probability','5'); ini_set('session.gc_probability','5');
if (!isset($results['memory_limit']) || if (!isset($results['memory_limit']) ||
(UI::unformat_bytes($results['memory_limit']) < UI::unformat_bytes('32M')) (UI::unformat_bytes($results['memory_limit']) < UI::unformat_bytes('32M'))
) { ) {
$results['memory_limit'] = '32M'; $results['memory_limit'] = '32M';
@ -153,8 +152,7 @@ if (!defined('NO_SESSION') && Config::get('use_auth')) {
/* Load preferences and theme */ /* Load preferences and theme */
$GLOBALS['user']->update_last_seen(); $GLOBALS['user']->update_last_seen();
} } elseif (!Config::get('use_auth')) {
elseif (!Config::get('use_auth')) {
$auth['success'] = 1; $auth['success'] = 1;
$auth['username'] = '-1'; $auth['username'] = '-1';
$auth['fullname'] = "Ampache User"; $auth['fullname'] = "Ampache User";
@ -169,13 +167,11 @@ elseif (!Config::get('use_auth')) {
$GLOBALS['user']->username = $auth['username']; $GLOBALS['user']->username = $auth['username'];
$GLOBALS['user']->fullname = $auth['fullname']; $GLOBALS['user']->fullname = $auth['fullname'];
$GLOBALS['user']->access = $auth['access']; $GLOBALS['user']->access = $auth['access'];
} } else {
else {
Session::check(); Session::check();
if ($_SESSION['userdata']['username']) { if ($_SESSION['userdata']['username']) {
$GLOBALS['user'] = User::get_from_username($_SESSION['userdata']['username']); $GLOBALS['user'] = User::get_from_username($_SESSION['userdata']['username']);
} } else {
else {
$GLOBALS['user'] = new User($auth['username']); $GLOBALS['user'] = new User($auth['username']);
$GLOBALS['user']->id = '-1'; $GLOBALS['user']->id = '-1';
$GLOBALS['user']->username = $auth['username']; $GLOBALS['user']->username = $auth['username'];
@ -195,8 +191,7 @@ else {
session_id(scrub_in($_REQUEST['sid'])); session_id(scrub_in($_REQUEST['sid']));
session_start(); session_start();
$GLOBALS['user'] = new User($_SESSION['userdata']['uid']); $GLOBALS['user'] = new User($_SESSION['userdata']['uid']);
} } else {
else {
$GLOBALS['user'] = new User(); $GLOBALS['user'] = new User();
} }
@ -238,4 +233,3 @@ $GLOBALS['xmlrpc_internalencoding'] = Config::get('site_charset');
if (Config::get('debug')) { if (Config::get('debug')) {
error_reporting(E_ALL); error_reporting(E_ALL);
} }
?>

View file

@ -24,30 +24,30 @@
* split_sql * split_sql
* splits up a standard SQL dump file into distinct sql queries * splits up a standard SQL dump file into distinct sql queries
*/ */
function split_sql($sql) { function split_sql($sql)
{
$sql = trim($sql); $sql = trim($sql);
$sql = preg_replace("/\n#[^\n]*\n/", "\n", $sql); $sql = preg_replace("/\n#[^\n]*\n/", "\n", $sql);
$buffer = array(); $buffer = array();
$ret = array(); $ret = array();
$in_string = false; $in_string = false;
for($i=0; $i<strlen($sql)-1; $i++) { for ($i=0; $i<strlen($sql)-1; $i++) {
if($sql[$i] == ";" && !$in_string) { if ($sql[$i] == ";" && !$in_string) {
$ret[] = substr($sql, 0, $i); $ret[] = substr($sql, 0, $i);
$sql = substr($sql, $i + 1); $sql = substr($sql, $i + 1);
$i = 0; $i = 0;
} }
if($in_string && ($sql[$i] == $in_string) && $buffer[1] != "\\") { if ($in_string && ($sql[$i] == $in_string) && $buffer[1] != "\\") {
$in_string = false; $in_string = false;
} } elseif (!$in_string && ($sql[$i] == '"' || $sql[$i] == "'") && (!isset($buffer[0]) || $buffer[0] != "\\")) {
elseif(!$in_string && ($sql[$i] == '"' || $sql[$i] == "'") && (!isset($buffer[0]) || $buffer[0] != "\\")) {
$in_string = $sql[$i]; $in_string = $sql[$i];
} }
if(isset($buffer[1])) { if (isset($buffer[1])) {
$buffer[0] = $buffer[1]; $buffer[0] = $buffer[1];
} }
$buffer[1] = $sql[$i]; $buffer[1] = $sql[$i];
} }
if(!empty($sql)) { if (!empty($sql)) {
$ret[] = $sql; $ret[] = $sql;
} }
return($ret); return($ret);
@ -59,8 +59,8 @@ function split_sql($sql) {
* still need to install ampache. This function is * still need to install ampache. This function is
* very important, we don't want to reinstall over top of an existing install * very important, we don't want to reinstall over top of an existing install
*/ */
function install_check_status($configfile) { function install_check_status($configfile)
{
/* /*
Check and see if the config file exists Check and see if the config file exists
if it does they can't use the web interface if it does they can't use the web interface
@ -94,8 +94,7 @@ function install_check_status($configfile) {
if (!Dba::num_rows($db_results)) { if (!Dba::num_rows($db_results)) {
return true; return true;
} } else {
else {
Error::add('general', T_('Existing Database detected, unable to continue installation')); Error::add('general', T_('Existing Database detected, unable to continue installation'));
return false; return false;
} }
@ -110,7 +109,8 @@ function install_check_status($configfile) {
* *
* Inserts the database using the values from Config. * Inserts the database using the values from Config.
*/ */
function install_insert_db($db_user = null, $db_pass = null, $overwrite = false, $use_existing_db = false) { function install_insert_db($db_user = null, $db_pass = null, $overwrite = false, $use_existing_db = false)
{
$database = Config::get('database_name'); $database = Config::get('database_name');
// Make sure that the database name is valid // Make sure that the database name is valid
$is_valid = preg_match('/([^\d\w\_\-])/', $database, $matches); $is_valid = preg_match('/([^\d\w\_\-])/', $database, $matches);
@ -131,11 +131,9 @@ function install_insert_db($db_user = null, $db_pass = null, $overwrite = false,
if ($db_exists) { if ($db_exists) {
if ($use_existing_db) { if ($use_existing_db) {
$create_db = false; $create_db = false;
} } else if ($overwrite) {
else if ($overwrite) {
Dba::write('DROP DATABASE `' . $database . '`'); Dba::write('DROP DATABASE `' . $database . '`');
} } else {
else {
Error::add('general', T_('Error: Database already exists and overwrite not checked')); Error::add('general', T_('Error: Database already exists and overwrite not checked'));
return false; return false;
} }
@ -171,7 +169,7 @@ function install_insert_db($db_user = null, $db_pass = null, $overwrite = false,
$pieces = split_sql($query); $pieces = split_sql($query);
for ($i=0; $i<count($pieces); $i++) { for ($i=0; $i<count($pieces); $i++) {
$pieces[$i] = trim($pieces[$i]); $pieces[$i] = trim($pieces[$i]);
if(!empty($pieces[$i]) && $pieces[$i] != '#') { if (!empty($pieces[$i]) && $pieces[$i] != '#') {
if (!$result = Dba::write($pieces[$i])) { if (!$result = Dba::write($pieces[$i])) {
$errors[] = array ( Dba::error(), $pieces[$i] ); $errors[] = array ( Dba::error(), $pieces[$i] );
} }
@ -198,15 +196,15 @@ function install_insert_db($db_user = null, $db_pass = null, $overwrite = false,
* *
* Attempts to write out the config file or offer it as a download. * Attempts to write out the config file or offer it as a download.
*/ */
function install_create_config($download = false) { function install_create_config($download = false)
{
$config_file = Config::get('prefix') . '/config/ampache.cfg.php'; $config_file = Config::get('prefix') . '/config/ampache.cfg.php';
/* Attempt to make DB connection */ /* Attempt to make DB connection */
$dbh = Dba::dbh(); $dbh = Dba::dbh();
// Connect to the DB // Connect to the DB
if(!Dba::check_database()) { if (!Dba::check_database()) {
Error::add('general', T_("Database Connection Failed Check Hostname, Username and Password")); Error::add('general', T_("Database Connection Failed Check Hostname, Username and Password"));
return false; return false;
} }
@ -218,16 +216,14 @@ function install_create_config($download = false) {
if (!check_config_writable()) { if (!check_config_writable()) {
Error::add('general', T_('Config file is not writable')); Error::add('general', T_('Config file is not writable'));
return false; return false;
} } else {
else {
// Given that $final is > 0, we can ignore lazy comparison problems // Given that $final is > 0, we can ignore lazy comparison problems
if (!file_put_contents($config_file, $final)) { if (!file_put_contents($config_file, $final)) {
Error::add('general', T_('Error writing config file')); Error::add('general', T_('Error writing config file'));
return false; return false;
} }
} }
} } else {
else {
$browser = new Horde_Browser(); $browser = new Horde_Browser();
$browser->downloadHeaders('ampache.cfg.php', 'text/plain', false, strlen($final)); $browser->downloadHeaders('ampache.cfg.php', 'text/plain', false, strlen($final));
echo $final; echo $final;
@ -241,8 +237,8 @@ function install_create_config($download = false) {
* install_create_account * install_create_account
* this creates your initial account and sets up the preferences for the -1 user and you * this creates your initial account and sets up the preferences for the -1 user and you
*/ */
function install_create_account($username, $password, $password2) { function install_create_account($username, $password, $password2)
{
if (!strlen($username) OR !strlen($password)) { if (!strlen($username) OR !strlen($password)) {
Error::add('general', T_('No Username/Password specified')); Error::add('general', T_('No Username/Password specified'));
return false; return false;
@ -279,5 +275,3 @@ function install_create_account($username, $password, $password2) {
return true; return true;
} // install_create_account } // install_create_account
?>

View file

@ -11,7 +11,7 @@
* *
* 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
@ -22,14 +22,14 @@
require_once '../init.php'; require_once '../init.php';
function arrayToJSON($array) { function arrayToJSON($array)
{
$json = '{ '; $json = '{ ';
foreach ($array as $key => $value) { foreach ($array as $key => $value) {
$json .= '"' . $key . '" : '; $json .= '"' . $key . '" : ';
if (is_array($value)) { if (is_array($value)) {
$json .= arrayToJSON($value); $json .= arrayToJSON($value);
} } else {
else {
// Make sure to strip backslashes and convert things to // Make sure to strip backslashes and convert things to
// entities in our output // entities in our output
$json .= '"' . scrub_out(str_replace('\\', '', $value)) . '"'; $json .= '"' . scrub_out(str_replace('\\', '', $value)) . '"';
@ -49,4 +49,3 @@ echo arrayToJSON($search->types) . "'.evalJSON());\n";
echo 'var basetypes = $H(\''; echo 'var basetypes = $H(\'';
echo arrayToJSON($search->basetypes) . "'.evalJSON());\n"; echo arrayToJSON($search->basetypes) . "'.evalJSON());\n";
echo 'removeIcon = \'<a href="javascript: void(0)">' . UI::get_icon('disable', T_('Remove')) . '</a>\';'; echo 'removeIcon = \'<a href="javascript: void(0)">' . UI::get_icon('disable', T_('Remove')) . '</a>\';';
?>

View file

@ -24,7 +24,8 @@
* log_event * log_event
* Logs an event to a defined log file based on config options * Logs an event to a defined log file based on config options
*/ */
function log_event($username, $event_name, $event_description, $log_name) { function log_event($username, $event_name, $event_description, $log_name)
{
/* Set it up here to make sure it's _always_ the same */ /* Set it up here to make sure it's _always_ the same */
$time = time(); $time = time();
// Turn time into strings // Turn time into strings
@ -53,7 +54,8 @@ function log_event($username, $event_name, $event_description, $log_name) {
* An error handler for ampache that traps as many errors as it can and logs * An error handler for ampache that traps as many errors as it can and logs
* them. * them.
*/ */
function ampache_error_handler($errno, $errstr, $errfile, $errline) { function ampache_error_handler($errno, $errstr, $errfile, $errline)
{
$level = 1; $level = 1;
switch ($errno) { switch ($errno) {
@ -100,7 +102,7 @@ function ampache_error_handler($errno, $errstr, $errfile, $errline) {
'used as offset, casting to integer' 'used as offset, casting to integer'
); );
foreach($ignores as $ignore) { foreach ($ignores as $ignore) {
if (strpos($errstr, $ignore) !== false) { if (strpos($errstr, $ignore) !== false) {
$error_name = 'Ignored ' . $error_name; $error_name = 'Ignored ' . $error_name;
$level = 7; $level = 7;
@ -127,8 +129,8 @@ function ampache_error_handler($errno, $errstr, $errfile, $errline) {
* log_event. It checks config for debug and debug_level and only * log_event. It checks config for debug and debug_level and only
* calls log event if both requirements are met. * calls log event if both requirements are met.
*/ */
function debug_event($type, $message, $level, $file = '', $username = '') { function debug_event($type, $message, $level, $file = '', $username = '')
{
if (!Config::get('debug') || $level > Config::get('debug_level')) { if (!Config::get('debug') || $level > Config::get('debug_level')) {
return false; return false;
} }
@ -143,5 +145,3 @@ function debug_event($type, $message, $level, $file = '', $username = '') {
} }
} // debug_event } // debug_event
?>

View file

@ -26,8 +26,8 @@
* 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 */
@ -63,8 +63,7 @@ function update_preferences($pref_id=0) {
} }
if (preg_match('/_pass$/', $name)) { if (preg_match('/_pass$/', $name)) {
if ($value == '******') { unset($_REQUEST[$name]); } if ($value == '******') { unset($_REQUEST[$name]); } else if (preg_match('/md5_pass$/', $name)) {
else if (preg_match('/md5_pass$/', $name)) {
$value = md5($value); $value = md5($value);
} }
} }
@ -89,8 +88,8 @@ 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;
@ -120,8 +119,8 @@ 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);
@ -131,22 +130,19 @@ function create_preference_input($name,$value) {
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 {
if (preg_match('/_pass$/', $name)) { if (preg_match('/_pass$/', $name)) {
echo "******"; echo "******";
} } else {
else {
echo $value; echo $value;
} }
} }
return; return;
} // if we don't have access to it } // if we don't have access to it
switch($name) { switch ($name) {
case 'display_menu': case 'display_menu':
case 'download': case 'download':
case 'quarantine': case 'quarantine':
@ -169,18 +165,14 @@ function create_preference_input($name,$value) {
case 'iframes': case 'iframes':
case 'now_playing_per_user': case 'now_playing_per_user':
case 'show_played_times': case 'show_played_times':
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>" . T_("Enable") . "</option>\n"; echo "\t<option value=\"1\" $is_true>" . T_("Enable") . "</option>\n";
echo "\t<option value=\"0\" $is_false>" . T_("Disable") . "</option>\n"; echo "\t<option value=\"0\" $is_false>" . T_("Disable") . "</option>\n";
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 == 'html5_player') { $is_html5_player = 'selected="selected"'; } else { $is_stream = "selected=\"selected\""; }
elseif ($value == 'democratic') { $is_vote = 'selected="selected"'; }
elseif ($value == 'html5_player') { $is_html5_player = 'selected="selected"'; }
else { $is_stream = "selected=\"selected\""; }
echo "<select name=\"$name\">\n"; echo "<select name=\"$name\">\n";
echo "\t<option value=\"\">" . T_('None') . "</option>\n"; echo "\t<option value=\"\">" . T_('None') . "</option>\n";
if (Config::get('allow_stream_playback')) { if (Config::get('allow_stream_playback')) {
@ -229,9 +221,7 @@ function create_preference_input($name,$value) {
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 == '50') { $is_manager = 'selected="selected"'; }
elseif ($value == '100') { $is_admin = 'selected="selected"'; }
elseif ($value == '50') { $is_manager = 'selected="selected"'; }
echo "<select name=\"$name\">\n"; echo "<select name=\"$name\">\n";
echo "<option value=\"0\">" . T_('Disabled') . "</option>\n"; echo "<option value=\"0\">" . T_('Disabled') . "</option>\n";
echo "<option value=\"25\" $is_user>" . T_('User') . "</option>\n"; echo "<option value=\"25\" $is_user>" . T_('User') . "</option>\n";
@ -283,20 +273,15 @@ function create_preference_input($name,$value) {
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>" . T_("Enable") . "</option>\n"; echo "\t<option value=\"1\" $is_true>" . T_("Enable") . "</option>\n";
echo "\t<option value=\"0\" $is_false>" . T_("Disable") . "</option>\n"; echo "\t<option value=\"0\" $is_false>" . T_("Disable") . "</option>\n";
echo "</select>\n"; echo "</select>\n";
break; break;
case 'album_sort': case 'album_sort':
if ($value == 'year_asc') { $is_sort_year_asc = 'selected="selected"'; } if ($value == 'year_asc') { $is_sort_year_asc = 'selected="selected"'; } elseif ($value == 'year_desc') { $is_sort_year_desc = 'selected="selected"'; } elseif ($value == 'name_asc') { $is_sort_name_asc = 'selected="selected"'; } elseif ($value == 'name_desc') { $is_sort_name_desc = 'selected="selected"'; } else { $is_sort_default = 'selected="selected"'; }
elseif ($value == 'year_desc') { $is_sort_year_desc = 'selected="selected"'; }
elseif ($value == 'name_asc') { $is_sort_name_asc = 'selected="selected"'; }
elseif ($value == 'name_desc') { $is_sort_name_desc = 'selected="selected"'; }
else { $is_sort_default = 'selected="selected"'; }
echo "<select name=\"$name\">\n"; echo "<select name=\"$name\">\n";
echo "\t<option value=\"default\" $is_sort_default>" . T_('Default') . "</option>\n"; echo "\t<option value=\"default\" $is_sort_default>" . T_('Default') . "</option>\n";
echo "\t<option value=\"year_asc\" $is_sort_year_asc>" . T_('Year ascending') . "</option>\n"; echo "\t<option value=\"year_asc\" $is_sort_year_asc>" . T_('Year ascending') . "</option>\n";
@ -308,8 +293,7 @@ function create_preference_input($name,$value) {
default: default:
if (preg_match('/_pass$/', $name)) { if (preg_match('/_pass$/', $name)) {
echo '<input type="password" size="16" name="' . $name . '" value="******" />'; echo '<input type="password" size="16" name="' . $name . '" value="******" />';
} } else {
else {
echo '<input type="text" size="' . $len . '" name="' . $name . '" value="' . $value .'" />'; echo '<input type="text" size="' . $len . '" name="' . $name . '" value="' . $value .'" />';
} }
break; break;
@ -317,5 +301,3 @@ function create_preference_input($name,$value) {
} }
} // create_preference_input } // create_preference_input
?>

View file

@ -24,8 +24,8 @@
* show_rating * show_rating
* This takes an artist id and includes the right file * This takes an artist id and includes the right file
*/ */
function show_rating($object_id,$type) { function show_rating($object_id,$type)
{
$rating = new Rating($object_id,$type); $rating = new Rating($object_id,$type);
require Config::get('prefix') . '/templates/show_object_rating.inc.php'; require Config::get('prefix') . '/templates/show_object_rating.inc.php';
@ -36,8 +36,8 @@ function show_rating($object_id,$type) {
* get_rating_name * get_rating_name
* This takes a score and returns the name that we should use * This takes a score and returns the name that we should use
*/ */
function get_rating_name($score) { function get_rating_name($score)
{
switch ($score) { switch ($score) {
case '0': case '0':
return T_("Don't Play"); return T_("Don't Play");
@ -66,5 +66,3 @@ function get_rating_name($score) {
return true; return true;
} // get_rating_name } // get_rating_name
?>

View file

@ -26,8 +26,8 @@
* theme.cfg.php files it can find and returns an * theme.cfg.php files it can find and returns an
* array of the results * array of the results
*/ */
function get_themes() { function get_themes()
{
/* Open the themes dir and start reading it */ /* Open the themes dir and start reading it */
$handle = opendir(Config::get('prefix') . '/themes'); $handle = opendir(Config::get('prefix') . '/themes');
@ -47,8 +47,7 @@ function get_themes() {
$r = parse_ini_file($file . $theme_cfg); $r = parse_ini_file($file . $theme_cfg);
$r['path'] = $f; $r['path'] = $f;
$results[$r['name']] = $r; $results[$r['name']] = $r;
} } else {
else {
debug_event('theme', "$theme_cfg not found in $f", 5); debug_event('theme', "$theme_cfg not found in $f", 5);
} }
} // end while directory } // end while directory
@ -65,8 +64,8 @@ function get_themes() {
@discussion get a single theme and read the config file @discussion get a single theme and read the config file
then return the results then return the results
*/ */
function get_theme($name) { function get_theme($name)
{
if (strlen($name) < 1) { return false; } if (strlen($name) < 1) { return false; }
$config_file = Config::get('prefix') . "/themes/" . $name . "/theme.cfg.php"; $config_file = Config::get('prefix') . "/themes/" . $name . "/theme.cfg.php";
@ -80,8 +79,8 @@ function get_theme($name) {
@function get_theme_author @function get_theme_author
@discussion returns the author of this theme @discussion returns the author of this theme
*/ */
function get_theme_author($theme_name) { function get_theme_author($theme_name)
{
$theme_path = Config::get('prefix') . '/themes/' . Config::get('theme_name') . '/theme.cfg.php'; $theme_path = Config::get('prefix') . '/themes/' . Config::get('theme_name') . '/theme.cfg.php';
$results = read_config($theme_path); $results = read_config($theme_path);
@ -93,8 +92,8 @@ function get_theme_author($theme_name) {
@function theme_exists @function theme_exists
@discussion this function checks to make sure that a theme actually exists @discussion this function checks to make sure that a theme actually exists
*/ */
function theme_exists($theme_name) { function theme_exists($theme_name)
{
$theme_path = Config::get('prefix') . '/themes/' . $theme_name . '/theme.cfg.php'; $theme_path = Config::get('prefix') . '/themes/' . $theme_name . '/theme.cfg.php';
if (!file_exists($theme_path)) { if (!file_exists($theme_path)) {
@ -104,5 +103,3 @@ function theme_exists($theme_name) {
return true; return true;
} // theme_exists } // theme_exists
?>

View file

@ -35,12 +35,11 @@
* @param integer $cancel T/F show a cancel button that uses return_referrer() * @param integer $cancel T/F show a cancel button that uses return_referrer()
* @return void * @return void
*/ */
function show_confirmation($title,$text,$next_url,$cancel=0,$form_name='confirmation') { function show_confirmation($title,$text,$next_url,$cancel=0,$form_name='confirmation')
{
if (substr_count($next_url,Config::get('web_path'))) { if (substr_count($next_url,Config::get('web_path'))) {
$path = $next_url; $path = $next_url;
} } else {
else {
$path = Config::get('web_path') . "/$next_url"; $path = Config::get('web_path') . "/$next_url";
} }
@ -54,13 +53,12 @@ function show_confirmation($title,$text,$next_url,$cancel=0,$form_name='confirma
* this is not %100 accurate. Also because this is not passed by us we need * this is not %100 accurate. Also because this is not passed by us we need
* to clean it up, take the filename then check for a /admin/ and dump the rest * to clean it up, take the filename then check for a /admin/ and dump the rest
*/ */
function return_referer() { function return_referer()
{
$referer = $_SERVER['HTTP_REFERER']; $referer = $_SERVER['HTTP_REFERER'];
if (substr($referer, -1)=='/'){ if (substr($referer, -1)=='/') {
$file = 'index.php'; $file = 'index.php';
} } 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));
@ -85,14 +83,13 @@ function return_referer() {
* ['page'] actual page name * ['page'] actual page name
* ['section'] name of the section we are in, admin, browse etc (submenu) * ['section'] name of the section we are in, admin, browse etc (submenu)
*/ */
function get_location() { 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'];
} }
@ -178,8 +175,8 @@ function get_location() {
* show_preference_box * show_preference_box
* This shows the preference box for the preferences pages. * This shows the preference box for the preferences pages.
*/ */
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
@ -189,9 +186,10 @@ function show_preference_box($preferences) {
* This displays a select of every album that we've got in Ampache (which can be * This displays a select of every album that we've got in Ampache (which can be
* hella long). It's used by the Edit page and takes a $name and a $album_id * hella long). It's used by the Edit page and 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; public static $id_cnt;
if ($song_id) { if ($song_id) {
$key = "album_select_$song_id"; $key = "album_select_$song_id";
} else { } else {
@ -229,9 +227,10 @@ function show_album_select($name='album',$album_id=0,$allow_add=0,$song_id=0) {
* This is the same as show_album_select except it's *gasp* for artists! How * This is the same as show_album_select except it's *gasp* for artists! How
* inventive! * 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; public static $id_cnt;
if ($song_id) { if ($song_id) {
$key = "artist_select_$song_id"; $key = "artist_select_$song_id";
} else { } else {
@ -268,8 +267,8 @@ function show_artist_select($name='artist', $artist_id=0, $allow_add=0, $song_id
* Yet another one of these buggers. this shows a drop down of all of your * Yet another one of these buggers. this shows a drop down of all of your
* catalogs. * 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`";
@ -294,8 +293,8 @@ 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=\"\">" . T_('All') . "</option>\n"; echo "\t<option value=\"\">" . T_('All') . "</option>\n";
@ -321,8 +320,8 @@ function show_user_select($name,$selected='',$style='') {
* show_playlist_select * show_playlist_select
* This one is for playlists! * This one is for playlists!
*/ */
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=\"\">" . T_('None') . "</option>\n"; echo "\t<option value=\"\">" . T_('None') . "</option>\n";
@ -348,8 +347,8 @@ function show_playlist_select($name,$selected='',$style='') {
* This takes a one dimensional array and creates a XML document from it. For * This takes a one dimensional array and creates a XML document from it. For
* use primarily by the ajax mojo. * use primarily by the ajax mojo.
*/ */
function xml_from_array($array, $callback = false, $type = '') { function xml_from_array($array, $callback = false, $type = '')
{
$string = ''; $string = '';
// If we weren't passed an array then return // If we weren't passed an array then return
@ -362,9 +361,8 @@ function xml_from_array($array, $callback = false, $type = '') {
if (is_array($value)) { if (is_array($value)) {
$value = xml_from_array($value,1,$type); $value = xml_from_array($value,1,$type);
$string .= "\t\t<$key>\n$value\t\t</$key>\n"; $string .= "\t\t<$key>\n$value\t\t</$key>\n";
} } else {
else { if ($key == "key") {
if ($key == "key"){
$string .= "\t\t<$key>$value</$key>\n"; $string .= "\t\t<$key>$value</$key>\n";
} elseif (is_int($value)) { } elseif (is_int($value)) {
$string .= "\t\t\t<key>$key</key><integer>$value</integer>\n"; $string .= "\t\t\t<key>$key</key><integer>$value</integer>\n";
@ -385,9 +383,8 @@ function xml_from_array($array, $callback = false, $type = '') {
if (is_array($value)) { if (is_array($value)) {
$value = xml_from_array($value,1,$type); $value = xml_from_array($value,1,$type);
$string .= "\t\t<$key>\n$value\t\t</$key>\n"; $string .= "\t\t<$key>\n$value\t\t</$key>\n";
} } else {
else { if ($key == "key") {
if ($key == "key"){
$string .= "\t\t<$key>$value</$key>\n"; $string .= "\t\t<$key>$value</$key>\n";
} elseif (is_numeric($value)) { } elseif (is_numeric($value)) {
$string .= "\t\t\t<$key>$value</$key>\n"; $string .= "\t\t\t<$key>$value</$key>\n";
@ -412,8 +409,7 @@ function xml_from_array($array, $callback = false, $type = '') {
// Call ourself // Call ourself
$value = xml_from_array($value, true); $value = xml_from_array($value, true);
$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";
} }
@ -433,8 +429,9 @@ function xml_from_array($array, $callback = false, $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) {
case 'itunes': case 'itunes':
$header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" . $header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" .
"<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\"\n" . "<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\"\n" .
@ -472,8 +469,9 @@ function xml_get_header($type){
* xml_get_footer * xml_get_footer
* This takes the type and returns the correct xml footer * This takes the type and returns the correct xml footer
*/ */
function xml_get_footer($type){ function xml_get_footer($type)
switch ($type){ {
switch ($type) {
case 'itunes': case 'itunes':
$footer = " </dict>\n" . $footer = " </dict>\n" .
"</dict>\n" . "</dict>\n" .
@ -495,8 +493,8 @@ function xml_get_footer($type){
* toggle_visible * toggle_visible
* This is identical to the javascript command that it actually calls * This is identical to the javascript command that it actually calls
*/ */
function toggle_visible($element) { function toggle_visible($element)
{
echo '<script type="text/javascript">'; echo '<script type="text/javascript">';
echo "toggleVisible('$element');"; echo "toggleVisible('$element');";
echo "</script>\n"; echo "</script>\n";
@ -508,12 +506,11 @@ function toggle_visible($element) {
* This function takes a boolean value and then prints out a friendly text * This function takes a boolean value and then prints out a friendly text
* message. * message.
*/ */
function print_bool($value) { function print_bool($value)
{
if ($value) { if ($value) {
$string = '<span class="item_on">' . T_('On') . '</span>'; $string = '<span class="item_on">' . T_('On') . '</span>';
} } else {
else {
$string = '<span class="item_off">' . T_('Off') . '</span>'; $string = '<span class="item_off">' . T_('Off') . '</span>';
} }
@ -526,8 +523,8 @@ function print_bool($value) {
* This shows the now playing templates and does some garbage collecion * This shows the now playing templates and does some garbage collecion
* this should really be somewhere else * this should really be somewhere else
*/ */
function show_now_playing() { function show_now_playing()
{
Session::gc(null); Session::gc(null);
Stream::gc_now_playing(); Stream::gc_now_playing();
@ -536,6 +533,3 @@ function show_now_playing() {
require_once Config::get('prefix') . '/templates/show_now_playing.inc.php'; require_once Config::get('prefix') . '/templates/show_now_playing.inc.php';
} // show_now_playing } // show_now_playing
?>

View file

@ -91,4 +91,3 @@ switch ($_REQUEST['action']) {
} // end switch action } // end switch action
UI::show_footer(); UI::show_footer();
?>

View file

@ -61,28 +61,24 @@ if (($_POST['username'] && $_POST['password']) ||
$auth['info']['username'] = 'Admin - DEMO'; $auth['info']['username'] = 'Admin - DEMO';
$auth['info']['fullname'] = 'Administrative User'; $auth['info']['fullname'] = 'Administrative User';
$auth['info']['offset_limit'] = 25; $auth['info']['offset_limit'] = 25;
} } else {
else {
if ($_POST['username'] && $_POST['password']) { if ($_POST['username'] && $_POST['password']) {
$username = scrub_in($_POST['username']); $username = scrub_in($_POST['username']);
$password = $_POST['password']; $password = $_POST['password'];
} } else {
else {
if ($_SERVER['REMOTE_USER']) { if ($_SERVER['REMOTE_USER']) {
$username = $_SERVER['REMOTE_USER']; $username = $_SERVER['REMOTE_USER'];
} } elseif ($_SERVER['HTTP_REMOTE_USER']) {
elseif ($_SERVER['HTTP_REMOTE_USER']) {
$username = $_SERVER['HTTP_REMOTE_USER']; $username = $_SERVER['HTTP_REMOTE_USER'];
} }
$password = ''; $password = '';
} }
$auth = Auth::login($username, $password); $auth = Auth::login($username, $password);
if ($auth['success']) { if ($auth['success']) {
$username = $auth['username']; $username = $auth['username'];
} } else {
else {
debug_event('Login', scrub_out($username) . ' attempted to login and failed', '1'); debug_event('Login', scrub_out($username) . ' attempted to login and failed', '1');
Error::add('general', T_('Error Username or Password incorrect, please try again')); Error::add('general', T_('Error Username or Password incorrect, please try again'));
} }
@ -107,18 +103,17 @@ if (($_POST['username'] && $_POST['password']) ||
! $user->username) { ! $user->username) {
/* This is run if we want to autocreate users who don't /* This is run if we want to autocreate users who don't
exist (useful for non-mysql auth) */ exist (useful for non-mysql auth) */
$access = Config::get('auto_user') $access = Config::get('auto_user')
? User::access_name_to_level(Config::get('auto_user')) ? User::access_name_to_level(Config::get('auto_user'))
: '5'; : '5';
$name = $auth['name']; $name = $auth['name'];
$email = $auth['email']; $email = $auth['email'];
/* Attempt to create the user */ /* Attempt to create the user */
if (User::create($username, $name, $email, if (User::create($username, $name, $email,
hash('sha256', mt_rand()), $access)) { hash('sha256', mt_rand()), $access)) {
$user = User::get_from_username($username); $user = User::get_from_username($username);
} } else {
else {
$auth['success'] = false; $auth['success'] = false;
Error::add('general', T_('Unable to create local account')); Error::add('general', T_('Unable to create local account'));
} }
@ -148,7 +143,7 @@ if ($auth['success']) {
$user->insert_ip_history(); $user->insert_ip_history();
} }
/* Make sure they are actually trying to get to this site and don't try /* Make sure they are actually trying to get to this site and don't try
* to redirect them back into an admin section * to redirect them back into an admin section
*/ */
$web_path = Config::get('web_path'); $web_path = Config::get('web_path');
@ -168,5 +163,3 @@ if ($auth['success']) {
} // auth success } // auth success
require Config::get('prefix') . '/templates/show_login_form.inc.php'; require Config::get('prefix') . '/templates/show_login_form.inc.php';
?>

View file

@ -28,4 +28,3 @@ require_once 'lib/init.php';
// To end a legitimate session, just call logout. // To end a legitimate session, just call logout.
Auth::logout('',false); Auth::logout('',false);
?>

View file

@ -47,7 +47,8 @@ switch ($action) {
require Config::get('prefix') . '/templates/show_lostpassword_form.inc.php'; require Config::get('prefix') . '/templates/show_lostpassword_form.inc.php';
} }
function send_newpassword($email,$current_ip){ function send_newpassword($email,$current_ip)
{
/* get the Client and set the new password */ /* get the Client and set the new password */
$client = User::get_from_email($email); $client = User::get_from_email($email);
if ($client->email == $email) { if ($client->email == $email) {
@ -69,4 +70,3 @@ function send_newpassword($email,$current_ip){
} }
return false; return false;
} }
?>

View file

@ -20,8 +20,8 @@
* *
*/ */
class AmpacheApi { class AmpacheApi
{
// General Settings // General Settings
private $server; private $server;
private $username; private $username;
@ -67,7 +67,8 @@ class AmpacheApi {
* away, otherwise we will simply return an object that can be reconfigured * away, otherwise we will simply return an object that can be reconfigured
* and manually connected. * and manually connected.
*/ */
public function __construct($config = array()) { public function __construct($config = array())
{
// See if we are setting debug first // See if we are setting debug first
if (isset($config['debug'])) { if (isset($config['debug'])) {
$this->_debug_output = $config['debug']; $this->_debug_output = $config['debug'];
@ -93,7 +94,8 @@ class AmpacheApi {
* *
* Make debugging all nice and pretty. * Make debugging all nice and pretty.
*/ */
private function _debug($source, $message, $level = 5) { private function _debug($source, $message, $level = 5)
{
if ($this->_debug_output) { if ($this->_debug_output) {
echo "$source :: $message\n"; echo "$source :: $message\n";
} }
@ -108,7 +110,8 @@ class AmpacheApi {
* *
* This attempts to connect to the Ampache instance. * This attempts to connect to the Ampache instance.
*/ */
public function connect() { public function connect()
{
$this->_debug('CONNECT', "Using $this->username / $this->password"); $this->_debug('CONNECT', "Using $this->username / $this->password");
// Set up the handshake // Set up the handshake
@ -148,7 +151,8 @@ class AmpacheApi {
* object. It doesn't really do anything fancy, but it's a separate function * object. It doesn't really do anything fancy, but it's a separate function
* so it can be called both from the constructor and directly. * so it can be called both from the constructor and directly.
*/ */
public function configure($config = array()) { public function configure($config = array())
{
$this->_debug('CONFIGURE', 'Checking passed config options'); $this->_debug('CONFIGURE', 'Checking passed config options');
if (!is_array($config)) { if (!is_array($config)) {
@ -164,13 +168,13 @@ class AmpacheApi {
if (isset($config['password'])) { if (isset($config['password'])) {
$this->password = htmlentities($config['password'], ENT_QUOTES, 'UTF-8'); $this->password = htmlentities($config['password'], ENT_QUOTES, 'UTF-8');
} }
if (isset($config['api_secure'])) { if (isset($config['api_secure'])) {
// This should be a boolean response // This should be a boolean response
$this->api_secure = $config['api_secure'] ? true : false; $this->api_secure = $config['api_secure'] ? true : false;
} }
$protocol = $this->api_secure ? 'https://' : 'http://'; $protocol = $this->api_secure ? 'https://' : 'http://';
if (isset($config['server'])) { if (isset($config['server'])) {
// Replace any http:// in the URL with '' // Replace any http:// in the URL with ''
$config['server'] = str_replace($protocol, '', $config['server']); $config['server'] = str_replace($protocol, '', $config['server']);
@ -194,7 +198,8 @@ class AmpacheApi {
* the state can be accessed externally so it could be used to check and see * the state can be accessed externally so it could be used to check and see
* where the API is at, at this moment * where the API is at, at this moment
*/ */
public function set_state($state) { public function set_state($state)
{
// Very simple for now, maybe we'll do something more with this later // Very simple for now, maybe we'll do something more with this later
$this->api_state = strtoupper($state); $this->api_state = strtoupper($state);
} }
@ -204,7 +209,8 @@ class AmpacheApi {
* *
* This returns the state of the API. * This returns the state of the API.
*/ */
public function state() { public function state()
{
return $this->api_state; return $this->api_state;
} }
@ -214,7 +220,8 @@ class AmpacheApi {
* Returns the information gathered by the handshake. * Returns the information gathered by the handshake.
* Not raw so we can format it if we want? * Not raw so we can format it if we want?
*/ */
public function info() { public function info()
{
if ($this->state() != 'CONNECTED') { if ($this->state() != 'CONNECTED') {
throw new Exception('AmpacheApi::info API in non-ready state, unable to return info'); throw new Exception('AmpacheApi::info API in non-ready state, unable to return info');
} }
@ -228,7 +235,8 @@ class AmpacheApi {
* This sends an API command with options to the currently connected * This sends an API command with options to the currently connected
* host. * host.
*/ */
public function send_command($command, $options = array()) { public function send_command($command, $options = array())
{
$this->_debug('SEND COMMAND', $command . ' ' . json_encode($options)); $this->_debug('SEND COMMAND', $command . ' ' . json_encode($options));
if ($this->state() != 'READY' AND $this->state() != 'CONNECTED') { if ($this->state() != 'READY' AND $this->state() != 'CONNECTED') {
@ -258,7 +266,7 @@ class AmpacheApi {
if ($this->api_auth) { if ($this->api_auth) {
$url .= '&auth=' . urlencode($this->api_auth) . '&username=' . urlencode($this->username); $url .= '&auth=' . urlencode($this->api_auth) . '&username=' . urlencode($this->username);
} }
$this->_debug('COMMAND URL', $url); $this->_debug('COMMAND URL', $url);
$data = file_get_contents($url); $data = file_get_contents($url);
@ -274,7 +282,8 @@ class AmpacheApi {
* commands for the current version of Ampache. If no version is known yet * commands for the current version of Ampache. If no version is known yet
* it should return FALSE for everything except ping and handshake. * it should return FALSE for everything except ping and handshake.
*/ */
public function validate_command($command) { public function validate_command($command)
{
// FIXME: actually do something // FIXME: actually do something
return true; return true;
} }
@ -286,7 +295,8 @@ class AmpacheApi {
* it does that it will clean up anything that was there before, so I hope * it does that it will clean up anything that was there before, so I hope
* you didn't want any of that. * you didn't want any of that.
*/ */
public function parse_response($response) { public function parse_response($response)
{
// Reset the results // Reset the results
$this->XML_results = array(); $this->XML_results = array();
$this->XML_position = 0; $this->XML_position = 0;
@ -307,7 +317,8 @@ class AmpacheApi {
* *
* This returns the last data we parsed. * This returns the last data we parsed.
*/ */
public function get_response() { public function get_response()
{
return $this->XML_results; return $this->XML_results;
} }
@ -318,8 +329,8 @@ class AmpacheApi {
* XML_create_parser * XML_create_parser
* This creates the xml parser and sets the options * This creates the xml parser and sets the options
*/ */
public function XML_create_parser() { public function XML_create_parser()
{
$this->XML_parser = xml_parser_create(); $this->XML_parser = xml_parser_create();
xml_parser_set_option($this->XML_parser,XML_OPTION_CASE_FOLDING,false); xml_parser_set_option($this->XML_parser,XML_OPTION_CASE_FOLDING,false);
xml_set_object($this->XML_parser,$this); xml_set_object($this->XML_parser,$this);
@ -332,51 +343,47 @@ class AmpacheApi {
* XML_cdata * XML_cdata
* This is called for the content of the XML tag * This is called for the content of the XML tag
*/ */
public function XML_cdata($parser,$cdata) { public function XML_cdata($parser,$cdata)
{
$cdata = trim($cdata); $cdata = trim($cdata);
if (!$this->XML_currentTag || !$cdata) { return false; } if (!$this->XML_currentTag || !$cdata) { return false; }
if ($this->XML_subTag) { if ($this->XML_subTag) {
$this->XML_results[$this->XML_position][$this->XML_currentTag][$this->XML_subTag] = $cdata; $this->XML_results[$this->XML_position][$this->XML_currentTag][$this->XML_subTag] = $cdata;
} } else {
else {
$this->XML_results[$this->XML_position][$this->XML_currentTag] = $cdata; $this->XML_results[$this->XML_position][$this->XML_currentTag] = $cdata;
} }
} // XML_cdata } // XML_cdata
public function XML_start_element($parser,$tag,$attributes) { public function XML_start_element($parser,$tag,$attributes)
{
// Skip it! // Skip it!
if (in_array($tag,$this->XML_skiptags)) { return false; } if (in_array($tag,$this->XML_skiptags)) { return false; }
if (!in_array($tag,$this->XML_parenttags) OR $this->XML_currentTag) { if (!in_array($tag,$this->XML_parenttags) OR $this->XML_currentTag) {
$this->XML_subTag = $tag; $this->XML_subTag = $tag;
} } else {
else {
$this->XML_currentTag = $tag; $this->XML_currentTag = $tag;
} }
if (count($attributes)) { if (count($attributes)) {
if (!$this->XML_subTag) { if (!$this->XML_subTag) {
$this->XML_results[$this->XML_position][$this->XML_currentTag]['self'] = $attributes; $this->XML_results[$this->XML_position][$this->XML_currentTag]['self'] = $attributes;
} } else {
else {
$this->XML_results[$this->XML_position][$this->XML_currentTag][$this->XML_subTag]['self'] = $attributes; $this->XML_results[$this->XML_position][$this->XML_currentTag][$this->XML_subTag]['self'] = $attributes;
} }
} }
} // start_element } // start_element
public function XML_end_element($parser,$tag) { public function XML_end_element($parser,$tag)
{
if ($tag != $this->XML_currentTag) { if ($tag != $this->XML_currentTag) {
$this->XML_subTag = false; $this->XML_subTag = false;
} } else {
else {
$this->XML_currentTag = false; $this->XML_currentTag = false;
$this->XML_position++; $this->XML_position++;
} }
@ -384,4 +391,3 @@ class AmpacheApi {
} // end_element } // end_element
} }
?>

View file

@ -19,7 +19,7 @@
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
* *
*/ */
require_once Config::get('prefix') . '/modules/Dropbox/autoload.php'; require_once Config::get('prefix') . '/modules/Dropbox/autoload.php';
/** /**
@ -28,48 +28,48 @@
* This class handles all actual work in regards to remote Dropbox catalogs. * This class handles all actual work in regards to remote Dropbox catalogs.
* *
*/ */
class Catalog_dropbox extends Catalog { class Catalog_dropbox extends Catalog
{
private $version = '000001'; private $version = '000001';
private $type = 'dropbox'; private $type = 'dropbox';
private $description = 'Remote Dropbox Catalog'; private $description = 'Remote Dropbox Catalog';
/** /**
* get_description * get_description
* This returns the description of this catalog * This returns the description of this catalog
*/ */
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
/** /**
* get_type * get_type
* This returns the current catalog type * This returns the current catalog type
*/ */
public function get_type() { public function get_type()
{
return $this->type; return $this->type;
} // get_type } // get_type
/** /**
* get_create_help * get_create_help
* This returns hints on catalog creation * This returns hints on catalog creation
*/ */
public function get_create_help() { public function get_create_help()
{
$help = "<ul><li>Go to https://www.dropbox.com/developers/apps/create</li>" . $help = "<ul><li>Go to https://www.dropbox.com/developers/apps/create</li>" .
"<li>Select 'Dropbox API app'</li>" . "<li>Select 'Dropbox API app'</li>" .
"<li>Select 'Files and datastores'</li>" . "<li>Select 'Files and datastores'</li>" .
@ -80,19 +80,19 @@ class Catalog_dropbox extends Catalog {
//"<li>Add the following OAuth redirect URIs: <i>" . Config::get('web_path') . "/admin/catalog.php</i></li>" . //"<li>Add the following OAuth redirect URIs: <i>" . Config::get('web_path') . "/admin/catalog.php</i></li>" .
"<li>Copy your App key and App secret here</li></ul>"; "<li>Copy your App key and App secret here</li></ul>";
return $help; return $help;
} // get_create_help } // get_create_help
/** /**
* is_installed * is_installed
* This returns true or false if remote catalog is installed * This returns true or false if remote catalog is installed
*/ */
public function is_installed() { public function is_installed()
{
$sql = "DESCRIBE `catalog_dropbox`";
$db_results = Dba::query($sql);
$sql = "DESCRIBE `catalog_dropbox`"; return Dba::num_rows($db_results);
$db_results = Dba::query($sql);
return Dba::num_rows($db_results);
} // is_installed } // is_installed
@ -101,33 +101,33 @@ class Catalog_dropbox extends Catalog {
* install * install
* This function installs the remote catalog * This function installs the remote catalog
*/ */
public function install() { public function install()
{
$sql = "CREATE TABLE `catalog_dropbox` (`id` INT( 11 ) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY , ". $sql = "CREATE TABLE `catalog_dropbox` (`id` INT( 11 ) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY , ".
"`apikey` VARCHAR( 255 ) COLLATE utf8_unicode_ci NOT NULL , " . "`apikey` VARCHAR( 255 ) COLLATE utf8_unicode_ci NOT NULL , " .
"`secret` VARCHAR( 255 ) COLLATE utf8_unicode_ci NOT NULL , " . "`secret` VARCHAR( 255 ) COLLATE utf8_unicode_ci NOT NULL , " .
"`path` VARCHAR( 255 ) COLLATE utf8_unicode_ci NOT NULL , " . "`path` VARCHAR( 255 ) COLLATE utf8_unicode_ci NOT NULL , " .
"`authtoken` VARCHAR( 255 ) COLLATE utf8_unicode_ci NOT NULL , " . "`authtoken` VARCHAR( 255 ) COLLATE utf8_unicode_ci NOT NULL , " .
"`getchunk` TINYINT(1) NOT NULL, " . "`getchunk` TINYINT(1) NOT NULL, " .
"`catalog_id` INT( 11 ) NOT NULL" . "`catalog_id` INT( 11 ) NOT NULL" .
") 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::query($sql);
return true; return true;
} // install } // install
public function catalog_fields() {
public function catalog_fields()
{
$fields['apikey'] = array('description' => T_('API Key'), 'type'=>'textbox'); $fields['apikey'] = array('description' => T_('API Key'), 'type'=>'textbox');
$fields['secret'] = array('description' => T_('Secret'), 'type'=>'password'); $fields['secret'] = array('description' => T_('Secret'), 'type'=>'password');
$fields['path'] = array('description' => T_('Path'), 'type'=>'textbox', 'value' => '/'); $fields['path'] = array('description' => T_('Path'), 'type'=>'textbox', 'value' => '/');
$fields['getchunk'] = array('description' => T_('Get chunked files on analyze'), 'type'=>'checkbox', 'value' => true); $fields['getchunk'] = array('description' => T_('Get chunked files on analyze'), 'type'=>'checkbox', 'value' => true);
return $fields; return $fields;
}
}
public $apikey; public $apikey;
public $secret; public $secret;
public $path; public $path;
@ -139,7 +139,8 @@ class Catalog_dropbox extends Catalog {
* *
* Catalog class constructor, pulls catalog information * Catalog class constructor, pulls catalog information
*/ */
public function __construct($catalog_id = null) { public function __construct($catalog_id = null)
{
if ($catalog_id) { if ($catalog_id) {
$this->id = intval($catalog_id); $this->id = intval($catalog_id);
$info = $this->get_info($catalog_id); $info = $this->get_info($catalog_id);
@ -157,24 +158,24 @@ class Catalog_dropbox extends Catalog {
* It checks to make sure its parameters is not already used before creating * It checks to make sure its parameters is not already used before creating
* the catalog. * the catalog.
*/ */
public static function create_type($catalog_id, $data) { public static function create_type($catalog_id, $data)
{
$apikey = $data['apikey']; $apikey = $data['apikey'];
$secret = $data['secret']; $secret = $data['secret'];
$path = $data['path']; $path = $data['path'];
$getchunk = $data['getchunk']; $getchunk = $data['getchunk'];
if (!strlen($apikey) OR !strlen($secret)) { if (!strlen($apikey) OR !strlen($secret)) {
Error::add('general', T_('Error: API Key and Secret Required for Dropbox Catalogs')); Error::add('general', T_('Error: API Key and Secret Required for Dropbox Catalogs'));
return false; return false;
} }
$pathError = Dropbox\Path::findError($path); $pathError = Dropbox\Path::findError($path);
if ($pathError !== null) { if ($pathError !== null) {
Error::add('general', T_('Invalid <dropbox-path>: ' . $pathError)); Error::add('general', T_('Invalid <dropbox-path>: ' . $pathError));
return false; return false;
} }
// Make sure this app isn't already in use by an existing catalog // Make sure this app isn't already in use by an existing catalog
$sql = 'SELECT `id` FROM `catalog_dropbox` WHERE `apikey` = ?'; $sql = 'SELECT `id` FROM `catalog_dropbox` WHERE `apikey` = ?';
$db_results = Dba::read($sql, array($apikey)); $db_results = Dba::read($sql, array($apikey));
@ -189,15 +190,17 @@ class Catalog_dropbox extends Catalog {
Dba::write($sql, array($apikey, $secret, $path, ($getchunk ? 1 : 0), $catalog_id)); Dba::write($sql, array($apikey, $secret, $path, ($getchunk ? 1 : 0), $catalog_id));
return true; return true;
} }
protected function getWebAuth() { protected function getWebAuth()
{
$appInfo = new Dropbox\AppInfo($this->apikey, $this->secret); $appInfo = new Dropbox\AppInfo($this->apikey, $this->secret);
$webAuth = new Dropbox\WebAuthNoRedirect($appInfo, "ampache", "en"); $webAuth = new Dropbox\WebAuthNoRedirect($appInfo, "ampache", "en");
return $webAuth; return $webAuth;
} }
protected function showAuthToken() { protected function showAuthToken()
{
$webAuth = $this->getWebAuth(); $webAuth = $this->getWebAuth();
$authurl = $webAuth->start(); $authurl = $webAuth->start();
echo "<br />Go to <strong><a href='" . $authurl . "' target='_blank'>" . $authurl . "</a></strong> to generate the authorization code, then enter it bellow.<br />"; echo "<br />Go to <strong><a href='" . $authurl . "' target='_blank'>" . $authurl . "</a></strong> to generate the authorization code, then enter it bellow.<br />";
@ -211,13 +214,14 @@ class Catalog_dropbox extends Catalog {
echo "</form>"; echo "</form>";
echo "<br />"; echo "<br />";
} }
protected function completeAuthToken() { protected function completeAuthToken()
{
$webAuth = $this->getWebAuth(); $webAuth = $this->getWebAuth();
list($accessToken, $userId) = $webAuth->finish($this->authcode); list($accessToken, $userId) = $webAuth->finish($this->authcode);
debug_event('dropbox_catalog', 'Dropbox authentication token generated for user ' . $userId . '.', 1); debug_event('dropbox_catalog', 'Dropbox authentication token generated for user ' . $userId . '.', 1);
$this->authtoken = $accessToken; $this->authtoken = $accessToken;
$sql = 'UPDATE `catalog_dropbox` SET `authtoken` = ? WHERE `catalog_id` = ?'; $sql = 'UPDATE `catalog_dropbox` SET `authtoken` = ? WHERE `catalog_id` = ?';
Dba::write($sql, array($this->authtoken, $this->catalog_id)); Dba::write($sql, array($this->authtoken, $this->catalog_id));
} }
@ -227,22 +231,24 @@ class Catalog_dropbox extends Catalog {
* this function adds new files to an * this function adds new files to an
* existing catalog * existing catalog
*/ */
public function add_to_catalog($options = null) { public function add_to_catalog($options = null)
{
// Prevent the script from timing out // Prevent the script from timing out
set_time_limit(0); set_time_limit(0);
if ($options != null) { if ($options != null) {
$this->authcode = $options['authcode']; $this->authcode = $options['authcode'];
} }
UI::show_box_top(T_('Running Dropbox Remote Update') . '. . .'); UI::show_box_top(T_('Running Dropbox Remote Update') . '. . .');
$this->update_remote_catalog(); $this->update_remote_catalog();
UI::show_box_bottom(); UI::show_box_bottom();
return true; return true;
} // add_to_catalog } // add_to_catalog
public function createClient() { public function createClient()
{
if ($this->authcode) { if ($this->authcode) {
$this->completeAuthToken(); $this->completeAuthToken();
} }
@ -250,7 +256,7 @@ class Catalog_dropbox extends Catalog {
$this->showAuthToken(); $this->showAuthToken();
return null; return null;
} }
try { try {
return new Dropbox\Client($this->authtoken, "ampache", "en"); return new Dropbox\Client($this->authtoken, "ampache", "en");
} catch (Dropbox\Exception $e) { } catch (Dropbox\Exception $e) {
@ -266,12 +272,13 @@ class Catalog_dropbox extends Catalog {
* Pulls the data from a remote catalog and adds any missing songs to the * Pulls the data from a remote catalog and adds any missing songs to the
* database. * database.
*/ */
public function update_remote_catalog() { public function update_remote_catalog()
{
$client = $this->createClient(); $client = $this->createClient();
if ($client != null) { if ($client != null) {
$this->count = 0; $this->count = 0;
$this->add_files($client, $this->path); $this->add_files($client, $this->path);
echo "\n<br />" . echo "\n<br />" .
printf(T_('Catalog Update Finished. Total Songs: [%s]'), $this->count); printf(T_('Catalog Update Finished. Total Songs: [%s]'), $this->count);
echo '<br />'; echo '<br />';
@ -279,7 +286,7 @@ class Catalog_dropbox extends Catalog {
echo T_('No songs updated, do you respect the patterns?') . '<br />'; echo T_('No songs updated, do you respect the patterns?') . '<br />';
} }
echo '<br />'; echo '<br />';
}else { } else {
echo "<p>" . T_('API Error: cannot connect to Dropbox.') . "</p><hr />\n"; echo "<p>" . T_('API Error: cannot connect to Dropbox.') . "</p><hr />\n";
flush(); flush();
} }
@ -287,13 +294,14 @@ class Catalog_dropbox extends Catalog {
return true; return true;
} }
/** /**
* add_files * add_files
* *
* Recurses through directories and pulls out all media files * Recurses through directories and pulls out all media files
*/ */
public function add_files($client, $path) { public function add_files($client, $path)
{
$metadata = $client->getMetadataWithChildren($path); $metadata = $client->getMetadataWithChildren($path);
if ($metadata != null) { if ($metadata != null) {
// If it's a folder, remove the 'contents' list from $metadata; print that stuff out after. // If it's a folder, remove the 'contents' list from $metadata; print that stuff out after.
@ -317,30 +325,31 @@ class Catalog_dropbox extends Catalog {
flush(); flush();
} }
} }
public function add_file($client, $data) { public function add_file($client, $data)
{
$file = $data['path']; $file = $data['path'];
$filesize = $data['bytes']; $filesize = $data['bytes'];
if ($filesize > 0) { if ($filesize > 0) {
$is_audio_file = Catalog::is_audio_file($file); $is_audio_file = Catalog::is_audio_file($file);
if ($is_audio_file) { if ($is_audio_file) {
$this->insert_song($client, $file, $filesize); $this->insert_song($client, $file, $filesize);
}else { } else {
debug_event('read', $data['path'] . " ignored, unknown media file type", 5); debug_event('read', $data['path'] . " ignored, unknown media file type", 5);
} }
} else { } else {
debug_event('read', $data['path'] . " ignored, 0 bytes", 5); debug_event('read', $data['path'] . " ignored, 0 bytes", 5);
} }
} }
/** /**
* _insert_local_song * _insert_local_song
* *
* Insert a song that isn't already in the database. * Insert a song that isn't already in the database.
*/ */
private function insert_song($client, $file, $filesize) { private function insert_song($client, $file, $filesize)
{
if ($this->check_remote_song($this->get_virtual_path($file))) { if ($this->check_remote_song($this->get_virtual_path($file))) {
debug_event('dropbox_catalog', 'Skipping existing song ' . $file, 5); debug_event('dropbox_catalog', 'Skipping existing song ' . $file, 5);
} else { } else {
@ -364,7 +373,7 @@ class Catalog_dropbox extends Catalog {
$key = vainfo::get_tag_type($vainfo->tags); $key = vainfo::get_tag_type($vainfo->tags);
$results = vainfo::clean_tag_info($vainfo->tags, $key, $file); $results = vainfo::clean_tag_info($vainfo->tags, $key, $file);
// Remove temp file // Remove temp file
if ($fpchunk) { if ($fpchunk) {
fclose($fpchunk); fclose($fpchunk);
@ -373,10 +382,10 @@ class Catalog_dropbox extends Catalog {
// Set the remote path // Set the remote path
$results['file'] = $origin; $results['file'] = $origin;
$results['catalog'] = $this->id; $results['catalog'] = $this->id;
if (!empty($results['artist']) && !empty($results['album'])) { if (!empty($results['artist']) && !empty($results['album'])) {
$results['file'] = $this->get_virtual_path($results['file']); $results['file'] = $this->get_virtual_path($results['file']);
Song::insert($results); Song::insert($results);
$this->count++; $this->count++;
} else { } else {
@ -384,17 +393,19 @@ class Catalog_dropbox extends Catalog {
} }
} }
} }
public function verify_catalog_proc() { public function verify_catalog_proc()
{
return array('total' => 0, 'updated' => 0); return array('total' => 0, 'updated' => 0);
} }
/** /**
* clean_catalog_proc * clean_catalog_proc
* *
* Removes songs that no longer exist. * Removes songs that no longer exist.
*/ */
public function clean_catalog_proc() { public function clean_catalog_proc()
{
$dead = 0; $dead = 0;
$client = $this->createClient(); $client = $this->createClient();
@ -407,8 +418,7 @@ class Catalog_dropbox extends Catalog {
$metadata = $client->getMetadata($file); $metadata = $client->getMetadata($file);
if ($metadata) { if ($metadata) {
debug_event('dropbox-clean', 'keeping song', 5, 'ampache-catalog'); debug_event('dropbox-clean', 'keeping song', 5, 'ampache-catalog');
} } else {
else {
debug_event('dropbox-clean', 'removing song', 5, 'ampache-catalog'); debug_event('dropbox-clean', 'removing song', 5, 'ampache-catalog');
$dead++; $dead++;
Dba::write('DELETE FROM `song` WHERE `id` = ?', array($row['id'])); Dba::write('DELETE FROM `song` WHERE `id` = ?', array($row['id']));
@ -418,7 +428,7 @@ class Catalog_dropbox extends Catalog {
echo "<p>" . T_('API Error: cannot connect to Dropbox.') . "</p><hr />\n"; echo "<p>" . T_('API Error: cannot connect to Dropbox.') . "</p><hr />\n";
flush(); flush();
} }
return $dead; return $dead;
} }
@ -428,8 +438,8 @@ class Catalog_dropbox extends Catalog {
* checks to see if a remote song exists in the database or not * checks to see if a remote song exists in the database or not
* if it find a song it returns the UID * if it find a song it returns the UID
*/ */
public function check_remote_song($file) { public function check_remote_song($file)
{
$sql = 'SELECT `id` FROM `song` WHERE `file` = ?'; $sql = 'SELECT `id` FROM `song` WHERE `file` = ?';
$db_results = Dba::read($sql, array($file)); $db_results = Dba::read($sql, array($file));
@ -439,53 +449,54 @@ class Catalog_dropbox extends Catalog {
return false; return false;
} }
public function get_virtual_path($file) { public function get_virtual_path($file)
{
return $this->apikey . '|' . $file; return $this->apikey . '|' . $file;
} }
public function get_rel_path($file_path) { public function get_rel_path($file_path)
{
$p = strpos($file_path, "|"); $p = strpos($file_path, "|");
if ($p !== false) { if ($p !== false) {
$p++; $p++;
} }
return substr($file_path, $p); return substr($file_path, $p);
} }
/** /**
* format * format
* *
* This makes the object human-readable. * This makes the object human-readable.
*/ */
public function format() { public function format()
{
parent::format(); parent::format();
$this->f_info = UI::truncate($this->apikey, Config::get('ellipse_threshold_title')); $this->f_info = UI::truncate($this->apikey, Config::get('ellipse_threshold_title'));
} }
public function prepare_media($media) { public function prepare_media($media)
{
$client = $this->createClient(); $client = $this->createClient();
if ($client != null) { if ($client != null) {
set_time_limit(0); set_time_limit(0);
// Generate browser class for sending headers // Generate browser class for sending headers
$browser = new Horde_Browser(); $browser = new Horde_Browser();
$media_name = $media->f_artist_full . " - " . $media->title . "." . $media->type; $media_name = $media->f_artist_full . " - " . $media->title . "." . $media->type;
$browser->downloadHeaders($media_name, $media->mime, false, $media->size); $browser->downloadHeaders($media_name, $media->mime, false, $media->size);
$file = $this->get_rel_path($media->file); $file = $this->get_rel_path($media->file);
$output = fopen('php://output', 'w'); $output = fopen('php://output', 'w');
$metadata = $client->getFile($file, $output); $metadata = $client->getFile($file, $output);
if ($metadata == null) { if ($metadata == null) {
debug_event('play', 'File not found on Dropbox: ' . $file, 5); debug_event('play', 'File not found on Dropbox: ' . $file, 5);
} }
fclose($output); fclose($output);
} }
return null; return null;
} }
} // end of catalog class } // end of catalog class
?>

View file

@ -26,48 +26,48 @@
* This class handles all actual work in regards to remote Google Music catalogs. * This class handles all actual work in regards to remote Google Music catalogs.
* *
*/ */
class Catalog_googlemusic extends Catalog { class Catalog_googlemusic extends Catalog
{
private $version = '000001'; private $version = '000001';
private $type = 'googlemusic'; private $type = 'googlemusic';
private $description = 'Remote Google Music Catalog'; private $description = 'Remote Google Music Catalog';
/** /**
* get_description * get_description
* This returns the description of this catalog * This returns the description of this catalog
*/ */
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
/** /**
* get_type * get_type
* This returns the current catalog type * This returns the current catalog type
*/ */
public function get_type() { public function get_type()
{
return $this->type; return $this->type;
} // get_type } // get_type
/** /**
* get_create_help * get_create_help
* This returns hints on catalog creation * This returns hints on catalog creation
*/ */
public function get_create_help() { public function get_create_help()
{
return ""; return "";
} // get_create_help } // get_create_help
@ -76,12 +76,12 @@ class Catalog_googlemusic extends Catalog {
* is_installed * is_installed
* This returns true or false if remote catalog is installed * This returns true or false if remote catalog is installed
*/ */
public function is_installed() { public function is_installed()
{
$sql = "DESCRIBE `catalog_googlemusic`";
$db_results = Dba::query($sql);
$sql = "DESCRIBE `catalog_googlemusic`"; return Dba::num_rows($db_results);
$db_results = Dba::query($sql);
return Dba::num_rows($db_results);
} // is_installed } // is_installed
@ -90,31 +90,31 @@ class Catalog_googlemusic extends Catalog {
* install * install
* This function installs the remote catalog * This function installs the remote catalog
*/ */
public function install() { public function install()
{
$sql = "CREATE TABLE `catalog_googlemusic` (`id` INT( 11 ) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY , ".
"`email` VARCHAR( 255 ) COLLATE utf8_unicode_ci NOT NULL , " .
"`password` VARCHAR( 255 ) COLLATE utf8_unicode_ci NOT NULL , " .
"`deviceid` VARCHAR( 255 ) COLLATE utf8_unicode_ci NULL , " .
"`catalog_id` INT( 11 ) NOT NULL" .
") ENGINE = MYISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
$db_results = Dba::query($sql);
$sql = "CREATE TABLE `catalog_googlemusic` (`id` INT( 11 ) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY , ". return true;
"`email` VARCHAR( 255 ) COLLATE utf8_unicode_ci NOT NULL , " .
"`password` VARCHAR( 255 ) COLLATE utf8_unicode_ci NOT NULL , " .
"`deviceid` VARCHAR( 255 ) COLLATE utf8_unicode_ci NULL , " .
"`catalog_id` INT( 11 ) NOT NULL" .
") ENGINE = MYISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
$db_results = Dba::query($sql);
return true;
} // install } // install
public function catalog_fields() {
public function catalog_fields()
{
$fields['email'] = array('description' => T_('Email'),'type'=>'textbox'); $fields['email'] = array('description' => T_('Email'),'type'=>'textbox');
$fields['password'] = array('description' => T_('Password'),'type'=>'password'); $fields['password'] = array('description' => T_('Password'),'type'=>'password');
// Device ID not required for streaming access // Device ID not required for streaming access
//$fields['deviceid'] = array('description' => T_('Device ID'),'type'=>'textbox'); //$fields['deviceid'] = array('description' => T_('Device ID'),'type'=>'textbox');
return $fields; return $fields;
}
}
public $email; public $email;
public $password; public $password;
public $deviceid; public $deviceid;
@ -124,7 +124,8 @@ class Catalog_googlemusic extends Catalog {
* *
* Catalog class constructor, pulls catalog information * Catalog class constructor, pulls catalog information
*/ */
public function __construct($catalog_id = null) { public function __construct($catalog_id = null)
{
if ($catalog_id) { if ($catalog_id) {
$this->id = intval($catalog_id); $this->id = intval($catalog_id);
$info = $this->get_info($catalog_id); $info = $this->get_info($catalog_id);
@ -133,7 +134,7 @@ class Catalog_googlemusic extends Catalog {
$this->$key = $value; $this->$key = $value;
} }
} }
require_once Config::get('prefix') . '/modules/GMApi/GMApi.php'; require_once Config::get('prefix') . '/modules/GMApi/GMApi.php';
} }
@ -144,17 +145,17 @@ class Catalog_googlemusic extends Catalog {
* It checks to make sure its parameters is not already used before creating * It checks to make sure its parameters is not already used before creating
* the catalog. * the catalog.
*/ */
public static function create_type($catalog_id, $data) { public static function create_type($catalog_id, $data)
{
$email = $data['email']; $email = $data['email'];
$password = $data['password']; $password = $data['password'];
$deviceid = $data['deviceid']; $deviceid = $data['deviceid'];
if (!strlen($email) OR !strlen($password)) { if (!strlen($email) OR !strlen($password)) {
Error::add('general', T_('Error: Email and Password Required for Google Music Catalogs')); Error::add('general', T_('Error: Email and Password Required for Google Music Catalogs'));
return false; return false;
} }
// Make sure this email isn't already in use by an existing catalog // Make sure this email isn't already in use by an existing catalog
$sql = 'SELECT `id` FROM `catalog_googlemusic` WHERE `email` = ?'; $sql = 'SELECT `id` FROM `catalog_googlemusic` WHERE `email` = ?';
$db_results = Dba::read($sql, array($email)); $db_results = Dba::read($sql, array($email));
@ -175,27 +176,28 @@ class Catalog_googlemusic extends Catalog {
* this function adds new files to an * this function adds new files to an
* existing catalog * existing catalog
*/ */
public function add_to_catalog($options = null) { public function add_to_catalog($options = null)
{
UI::show_box_top(T_('Running Google Music Remote Update') . '. . .'); UI::show_box_top(T_('Running Google Music Remote Update') . '. . .');
$this->update_remote_catalog(); $this->update_remote_catalog();
UI::show_box_bottom(); UI::show_box_bottom();
return true; return true;
} // add_to_catalog } // add_to_catalog
public function createClient() { public function createClient()
{
$api = new GMApi(); $api = new GMApi();
$api->setDebug(Config::get('debug')); $api->setDebug(Config::get('debug'));
$api->enableRestore(false); $api->enableRestore(false);
$api->enableMACAddressCheck(false); $api->enableMACAddressCheck(false);
$api->enableSessionFile(false); $api->enableSessionFile(false);
if(!$api->login($this->email, $this->password, $this->deviceid)) { if (!$api->login($this->email, $this->password, $this->deviceid)) {
debug_event('googlemusic_catalog', 'Google Music authentication failed.', 1); debug_event('googlemusic_catalog', 'Google Music authentication failed.', 1);
return null; return null;
} }
return $api; return $api;
} }
@ -205,7 +207,8 @@ class Catalog_googlemusic extends Catalog {
* Pulls the data from a remote catalog and adds any missing songs to the * Pulls the data from a remote catalog and adds any missing songs to the
* database. * database.
*/ */
public function update_remote_catalog() { public function update_remote_catalog()
{
$api = $this->createClient(); $api = $this->createClient();
if ($api != null) { if ($api != null) {
$songsadded = 0; $songsadded = 0;
@ -229,8 +232,7 @@ class Catalog_googlemusic extends Catalog {
$data['file'] = $this->email . '/' . $song['id']; $data['file'] = $this->email . '/' . $song['id'];
if ($this->check_remote_song($data)) { if ($this->check_remote_song($data)) {
debug_event('googlemusic_catalog', 'Skipping existing song ' . $data['file'], 5); debug_event('googlemusic_catalog', 'Skipping existing song ' . $data['file'], 5);
} } else {
else {
$data['catalog'] = $this->id; $data['catalog'] = $this->id;
debug_event('googlemusic_catalog', 'Adding song ' . $song['file'], 5, 'ampache-catalog'); debug_event('googlemusic_catalog', 'Adding song ' . $song['file'], 5, 'ampache-catalog');
if (!Song::insert($data)) { if (!Song::insert($data)) {
@ -243,7 +245,7 @@ class Catalog_googlemusic extends Catalog {
} }
} }
} }
echo "<p>" . T_('Completed updating Google Music catalog(s).') . " " . $songsadded . " " . T_('Songs added.') . "</p><hr />\n"; echo "<p>" . T_('Completed updating Google Music catalog(s).') . " " . $songsadded . " " . T_('Songs added.') . "</p><hr />\n";
flush(); flush();
@ -253,7 +255,7 @@ class Catalog_googlemusic extends Catalog {
echo "<p>" . T_('API Error: cannot connect song list.') . "</p><hr />\n"; echo "<p>" . T_('API Error: cannot connect song list.') . "</p><hr />\n";
flush(); flush();
} }
}else { } else {
echo "<p>" . T_('API Error: cannot connect to Google Music.') . "</p><hr />\n"; echo "<p>" . T_('API Error: cannot connect to Google Music.') . "</p><hr />\n";
flush(); flush();
} }
@ -261,17 +263,19 @@ class Catalog_googlemusic extends Catalog {
return true; return true;
} }
public function verify_catalog_proc() { public function verify_catalog_proc()
{
return array('total' => 0, 'updated' => 0); return array('total' => 0, 'updated' => 0);
} }
/** /**
* clean_catalog_proc * clean_catalog_proc
* *
* Removes songs that no longer exist. * Removes songs that no longer exist.
*/ */
public function clean_catalog_proc() { public function clean_catalog_proc()
{
$api = $this->createClient(); $api = $this->createClient();
$dead = 0; $dead = 0;
if ($api != null) { if ($api != null) {
@ -281,15 +285,14 @@ class Catalog_googlemusic extends Catalog {
foreach ($songs as $song) { foreach ($songs as $song) {
$files[] = $this->email . '/' . $song['id']; $files[] = $this->email . '/' . $song['id'];
} }
$sql = 'SELECT `id`, `file` FROM `song` WHERE `catalog` = ?'; $sql = 'SELECT `id`, `file` FROM `song` WHERE `catalog` = ?';
$db_results = Dba::read($sql, array($this->id)); $db_results = Dba::read($sql, array($this->id));
while ($row = Dba::fetch_assoc($db_results)) { while ($row = Dba::fetch_assoc($db_results)) {
debug_event('googlemusic-clean', 'Starting work on ' . $row['file'] . '(' . $row['id'] . ')', 5, 'ampache-catalog'); debug_event('googlemusic-clean', 'Starting work on ' . $row['file'] . '(' . $row['id'] . ')', 5, 'ampache-catalog');
if (in_array($row['file'], $files)) { if (in_array($row['file'], $files)) {
debug_event('googlemusic-clean', 'keeping song', 5, 'ampache-catalog'); debug_event('googlemusic-clean', 'keeping song', 5, 'ampache-catalog');
} } else {
else {
debug_event('googlemusic-clean', 'removing song', 5, 'ampache-catalog'); debug_event('googlemusic-clean', 'removing song', 5, 'ampache-catalog');
$dead++; $dead++;
Dba::write('DELETE FROM `song` WHERE `id` = ?', array($row['id'])); Dba::write('DELETE FROM `song` WHERE `id` = ?', array($row['id']));
@ -307,7 +310,8 @@ class Catalog_googlemusic extends Catalog {
* checks to see if a remote song exists in the database or not * checks to see if a remote song exists in the database or not
* if it find a song it returns the UID * if it find a song it returns the UID
*/ */
public function check_remote_song($song) { public function check_remote_song($song)
{
$url = $song['file']; $url = $song['file'];
$sql = 'SELECT `id` FROM `song` WHERE `file` = ?'; $sql = 'SELECT `id` FROM `song` WHERE `file` = ?';
@ -319,14 +323,16 @@ class Catalog_googlemusic extends Catalog {
return false; return false;
} }
public function get_rel_path($file_path) { public function get_rel_path($file_path)
{
$info = $this->_get_info(); $info = $this->_get_info();
$catalog_path = rtrim($info->email, "/"); $catalog_path = rtrim($info->email, "/");
return( str_replace( $catalog_path . "/", "", $file_path ) ); return( str_replace( $catalog_path . "/", "", $file_path ) );
} }
public function url_to_songid($url) { public function url_to_songid($url)
{
$id = 0; $id = 0;
$info = explode('/', $url); $info = explode('/', $url);
if (count($info) > 1) { if (count($info) > 1) {
@ -334,35 +340,34 @@ class Catalog_googlemusic extends Catalog {
} }
return $id; return $id;
} }
/** /**
* format * format
* *
* This makes the object human-readable. * This makes the object human-readable.
*/ */
public function format() { public function format()
{
parent::format(); parent::format();
$this->f_info = UI::truncate($this->email, Config::get('ellipse_threshold_title')); $this->f_info = UI::truncate($this->email, Config::get('ellipse_threshold_title'));
} }
public function prepare_media($media) { public function prepare_media($media)
{
$api = $this->createClient(); $api = $this->createClient();
if ($api != null) { if ($api != null) {
$songid = $this->url_to_songid($media->file); $songid = $this->url_to_songid($media->file);
$song = $api->get_stream_url($songid); $song = $api->get_stream_url($songid);
if ($song) { if ($song) {
header('Location: ' . $song); header('Location: ' . $song);
debug_event('play', 'Started remote stream - ' . $song, 5); debug_event('play', 'Started remote stream - ' . $song, 5);
} else { } else {
debug_event('play', 'Cannot get remote stream for song ' . $media->file, 5); debug_event('play', 'Cannot get remote stream for song ' . $media->file, 5);
} }
} }
return null; return null;
} }
} // end of catalog class } // end of catalog class
?>

View file

@ -26,48 +26,48 @@
* This class handles all actual work in regards to local catalogs. * This class handles all actual work in regards to local catalogs.
* *
*/ */
class Catalog_local extends Catalog { class Catalog_local extends Catalog
{
private $version = '000001'; private $version = '000001';
private $type = 'local'; private $type = 'local';
private $description = 'Local Catalog'; private $description = 'Local Catalog';
/** /**
* get_description * get_description
* This returns the description of this catalog * This returns the description of this catalog
*/ */
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
/** /**
* get_type * get_type
* This returns the current catalog type * This returns the current catalog type
*/ */
public function get_type() { public function get_type()
{
return $this->type; return $this->type;
} // get_type } // get_type
/** /**
* get_create_help * get_create_help
* This returns hints on catalog creation * This returns hints on catalog creation
*/ */
public function get_create_help() { public function get_create_help()
{
return ""; return "";
} // get_create_help } // get_create_help
@ -76,12 +76,12 @@ class Catalog_local extends Catalog {
* is_installed * is_installed
* This returns true or false if local catalog is installed * This returns true or false if local catalog is installed
*/ */
public function is_installed() { public function is_installed()
{
$sql = "DESCRIBE `catalog_local`";
$db_results = Dba::query($sql);
$sql = "DESCRIBE `catalog_local`"; return Dba::num_rows($db_results);
$db_results = Dba::query($sql);
return Dba::num_rows($db_results);
} // is_installed } // is_installed
@ -90,26 +90,26 @@ class Catalog_local extends Catalog {
* install * install
* This function installs the local catalog * This function installs the local catalog
*/ */
public function install() { public function install()
{
$sql = "CREATE TABLE `catalog_local` (`id` INT( 11 ) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY , ". $sql = "CREATE TABLE `catalog_local` (`id` INT( 11 ) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY , ".
"`path` VARCHAR( 255 ) COLLATE utf8_unicode_ci NOT NULL , " . "`path` VARCHAR( 255 ) COLLATE utf8_unicode_ci NOT NULL , " .
"`catalog_id` INT( 11 ) NOT NULL" . "`catalog_id` INT( 11 ) NOT NULL" .
") 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::query($sql);
return true; return true;
} // install } // install
public function catalog_fields() {
public function catalog_fields()
{
$fields['path'] = array('description' => T_('Path'),'type'=>'textbox'); $fields['path'] = array('description' => T_('Path'),'type'=>'textbox');
return $fields; return $fields;
}
}
public $path; public $path;
/** /**
@ -117,7 +117,8 @@ class Catalog_local extends Catalog {
* *
* Catalog class constructor, pulls catalog information * Catalog class constructor, pulls catalog information
*/ */
public function __construct($catalog_id = null) { public function __construct($catalog_id = null)
{
if ($catalog_id) { if ($catalog_id) {
$this->id = intval($catalog_id); $this->id = intval($catalog_id);
$info = $this->get_info($catalog_id); $info = $this->get_info($catalog_id);
@ -135,7 +136,8 @@ class Catalog_local extends Catalog {
* This is useful when creating a new catalog to make sure we're not * This is useful when creating a new catalog to make sure we're not
* doubling up here. * doubling up here.
*/ */
public static function get_from_path($path) { public static function get_from_path($path)
{
// First pull a list of all of the paths for the different catalogs // First pull a list of all of the paths for the different catalogs
$sql = "SELECT `catalog_id`,`path` FROM `catalog_local`"; $sql = "SELECT `catalog_id`,`path` FROM `catalog_local`";
$db_results = Dba::read($sql); $db_results = Dba::read($sql);
@ -169,15 +171,16 @@ class Catalog_local extends Catalog {
* It checks to make sure its parameters is not already used before creating * It checks to make sure its parameters is not already used before creating
* the catalog. * the catalog.
*/ */
public static function create_type($catalog_id, $data) { public static function create_type($catalog_id, $data)
{
// Clean up the path just in case // Clean up the path just in case
$path = rtrim(rtrim(trim($data['path']),'/'),'\\'); $path = rtrim(rtrim(trim($data['path']),'/'),'\\');
if (!strlen($path)) { if (!strlen($path)) {
Error::add('general', T_('Error: Path not specified')); Error::add('general', T_('Error: Path not specified'));
return false; return false;
} }
// Make sure that there isn't a catalog with a directory above this one // Make sure that there isn't a catalog with a directory above this one
if (self::get_from_path($path)) { if (self::get_from_path($path)) {
Error::add('general', T_('Error: Defined Path is inside an existing catalog')); Error::add('general', T_('Error: Defined Path is inside an existing catalog'));
@ -213,8 +216,8 @@ class Catalog_local extends Catalog {
* full path in an array. Passes gather_type to determine if we need to * full path in an array. Passes gather_type to determine if we need to
* check id3 information against the db. * check id3 information against the db.
*/ */
public function add_files($path, $options) { public function add_files($path, $options)
{
// Profile the memory a bit // Profile the memory a bit
debug_event('Memory', UI::format_bytes(memory_get_usage(true)), 5); debug_event('Memory', UI::format_bytes(memory_get_usage(true)), 5);
@ -227,8 +230,7 @@ class Catalog_local extends Catalog {
// Correctly detect the slash we need to use here // Correctly detect the slash we need to use here
if (strpos($path, '/') !== false) { if (strpos($path, '/') !== false) {
$slash_type = '/'; $slash_type = '/';
} } else {
else {
$slash_type = '\\'; $slash_type = '\\';
} }
@ -339,12 +341,11 @@ class Catalog_local extends Catalog {
else { else {
if ($is_audio_file) { if ($is_audio_file) {
$this->_insert_local_song($full_file,$file_size); $this->_insert_local_song($full_file,$file_size);
} } else { $this->insert_local_video($full_file,$file_size); }
else { $this->insert_local_video($full_file,$file_size); }
$this->count++; $this->count++;
$file = str_replace(array('(',')','\''),'',$full_file); $file = str_replace(array('(',')','\''),'',$full_file);
if(UI::check_ticker()) { if (UI::check_ticker()) {
UI::update_text('add_count_' . $this->id, $this->count); UI::update_text('add_count_' . $this->id, $this->count);
UI::update_text('add_dir_' . $this->id, scrub_out($file)); UI::update_text('add_dir_' . $this->id, scrub_out($file));
} // update our current state } // update our current state
@ -371,21 +372,21 @@ class Catalog_local extends Catalog {
@closedir($handle); @closedir($handle);
} // add_files } // add_files
/** /**
* add_to_catalog * add_to_catalog
* this function adds new files to an * this function adds new files to an
* existing catalog * existing catalog
*/ */
public function add_to_catalog($options = null) { public function add_to_catalog($options = null)
{
if ($options == null) { if ($options == null) {
$options = array( $options = array(
'gather_art' => true, 'gather_art' => true,
'parse_m3u' => true 'parse_m3u' => true
); );
} }
require Config::get('prefix') . '/templates/show_adds_catalog.inc.php'; require Config::get('prefix') . '/templates/show_adds_catalog.inc.php';
flush(); flush();
@ -436,13 +437,13 @@ class Catalog_local extends Catalog {
UI::show_box_bottom(); UI::show_box_bottom();
} // add_to_catalog } // add_to_catalog
/** /**
* verify_catalog_proc * verify_catalog_proc
* This function compares the DB's information with the ID3 tags * This function compares the DB's information with the ID3 tags
*/ */
public function verify_catalog_proc() { public function verify_catalog_proc()
{
debug_event('verify', 'Starting on ' . $this->name, 5); debug_event('verify', 'Starting on ' . $this->name, 5);
set_time_limit(0); set_time_limit(0);
@ -452,13 +453,13 @@ class Catalog_local extends Catalog {
require_once Config::get('prefix') . '/templates/show_verify_catalog.inc.php'; require_once Config::get('prefix') . '/templates/show_verify_catalog.inc.php';
foreach(array('video', 'song') as $media_type) { foreach (array('video', 'song') as $media_type) {
$total = $stats[$media_type . 's']; // UGLY $total = $stats[$media_type . 's']; // UGLY
if ($total == 0) { if ($total == 0) {
continue; continue;
} }
$chunks = floor($total / 10000); $chunks = floor($total / 10000);
foreach(range(0, $chunks) as $chunk) { foreach (range(0, $chunks) as $chunk) {
// Try to be nice about memory usage // Try to be nice about memory usage
if ($chunk > 0) { if ($chunk > 0) {
$media_type::clear_cache(); $media_type::clear_cache();
@ -471,7 +472,7 @@ class Catalog_local extends Catalog {
self::gc(); self::gc();
$this->update_last_update(); $this->update_last_update();
return array('total' => $number, 'updated' => $total_updated); return array('total' => $number, 'updated' => $total_updated);
} // verify_catalog_proc } // verify_catalog_proc
@ -481,7 +482,8 @@ class Catalog_local extends Catalog {
* This verifies a chunk of the catalog, done to save * This verifies a chunk of the catalog, done to save
* memory * memory
*/ */
private function _verify_chunk($media_type, $chunk, $chunk_size) { private function _verify_chunk($media_type, $chunk, $chunk_size)
{
debug_event('verify', "Starting chunk $chunk", 5); debug_event('verify', "Starting chunk $chunk", 5);
$count = $chunk * $chunk_size; $count = $chunk * $chunk_size;
$changed = 0; $changed = 0;
@ -496,9 +498,7 @@ class Catalog_local extends Catalog {
} }
$media_type::build_cache($media_ids); $media_type::build_cache($media_ids);
$db_results = Dba::read($sql); $db_results = Dba::read($sql);
} } while ($row = Dba::fetch_assoc($db_results)) {
while ($row = Dba::fetch_assoc($db_results)) {
$count++; $count++;
if (UI::check_ticker()) { if (UI::check_ticker()) {
$file = str_replace(array('(',')','\''), '', $row['file']); $file = str_replace(array('(',')','\''), '', $row['file']);
@ -536,7 +536,8 @@ class Catalog_local extends Catalog {
* *
* Removes local songs that no longer exist. * Removes local songs that no longer exist.
*/ */
public function clean_catalog_proc() { public function clean_catalog_proc()
{
if (!Core::is_readable($this->path)) { if (!Core::is_readable($this->path)) {
// First sanity check; no point in proceeding with an unreadable // First sanity check; no point in proceeding with an unreadable
// catalog root. // catalog root.
@ -548,14 +549,14 @@ class Catalog_local extends Catalog {
$dead_total = 0; $dead_total = 0;
$stats = self::get_stats($this->id); $stats = self::get_stats($this->id);
foreach(array('video', 'song') as $media_type) { foreach (array('video', 'song') as $media_type) {
$total = $stats[$media_type . 's']; // UGLY $total = $stats[$media_type . 's']; // UGLY
if ($total == 0) { if ($total == 0) {
continue; continue;
} }
$chunks = floor($total / 10000); $chunks = floor($total / 10000);
$dead = array(); $dead = array();
foreach(range(0, $chunks) as $chunk) { foreach (range(0, $chunks) as $chunk) {
$dead = array_merge($dead, $this->_clean_chunk($media_type, $chunk, 10000)); $dead = array_merge($dead, $this->_clean_chunk($media_type, $chunk, 10000));
} }
@ -576,13 +577,14 @@ class Catalog_local extends Catalog {
} }
return $dead_total; return $dead_total;
} }
/** /**
* _clean_chunk * _clean_chunk
* This is the clean function, its broken into * This is the clean function, its broken into
* said chunks to try to save a little memory * said chunks to try to save a little memory
*/ */
private function _clean_chunk($media_type, $chunk, $chunk_size) { private function _clean_chunk($media_type, $chunk, $chunk_size)
{
debug_event('clean', "Starting chunk $chunk", 5); debug_event('clean', "Starting chunk $chunk", 5);
$dead = array(); $dead = array();
$count = $chunk * $chunk_size; $count = $chunk * $chunk_size;
@ -622,7 +624,8 @@ class Catalog_local extends Catalog {
* *
* Insert a song that isn't already in the database. * Insert a song that isn't already in the database.
*/ */
private function _insert_local_song($file, $file_info) { private function _insert_local_song($file, $file_info)
{
$vainfo = new vainfo($file, '', '', '', $this->sort_pattern, $this->rename_pattern); $vainfo = new vainfo($file, '', '', '', $this->sort_pattern, $this->rename_pattern);
$vainfo->get_info(); $vainfo->get_info();
@ -639,8 +642,8 @@ class Catalog_local extends Catalog {
* information we can get is super sketchy so it's kind of a crap shoot * information we can get is super sketchy so it's kind of a crap shoot
* here * here
*/ */
public function insert_local_video($file,$filesize) { public function insert_local_video($file,$filesize)
{
/* Create the vainfo object and get info */ /* Create the vainfo object and get info */
$vainfo = new vainfo($file,'','','',$this->sort_pattern,$this->rename_pattern); $vainfo = new vainfo($file,'','','',$this->sort_pattern,$this->rename_pattern);
$vainfo->get_info(); $vainfo->get_info();
@ -668,8 +671,8 @@ class Catalog_local extends Catalog {
* check_local_mp3 * check_local_mp3
* Checks the song to see if it's there already returns true if found, false if not * Checks the song to see if it's there already returns true if found, false if not
*/ */
public function check_local_mp3($full_file, $gather_type='') { public function check_local_mp3($full_file, $gather_type='')
{
$file_date = filemtime($full_file); $file_date = filemtime($full_file);
if ($file_date < $this->last_add) { if ($file_date < $this->last_add) {
debug_event('Check','Skipping ' . $full_file . ' File modify time before last add run','3'); debug_event('Check','Skipping ' . $full_file . ' File modify time before last add run','3');
@ -687,28 +690,29 @@ class Catalog_local extends Catalog {
return false; return false;
} //check_local_mp3 } //check_local_mp3
public function get_rel_path($file_path) { public function get_rel_path($file_path)
{
$info = $this->_get_info(); $info = $this->_get_info();
$catalog_path = rtrim($info->path, "/"); $catalog_path = rtrim($info->path, "/");
return( str_replace( $catalog_path . "/", "", $file_path ) ); return( str_replace( $catalog_path . "/", "", $file_path ) );
} }
/** /**
* format * format
* *
* This makes the object human-readable. * This makes the object human-readable.
*/ */
public function format() { public function format()
{
parent::format(); parent::format();
$this->f_info = UI::truncate($this->path, Config::get('ellipse_threshold_title')); $this->f_info = UI::truncate($this->path, Config::get('ellipse_threshold_title'));
} }
public function prepare_media($media) { public function prepare_media($media)
{
// Do nothing, it's just file... // Do nothing, it's just file...
return $media; return $media;
} }
} // end of local catalog class } // end of local catalog class
?>

View file

@ -26,48 +26,48 @@
* This class handles all actual work in regards to remote catalogs. * This class handles all actual work in regards to remote catalogs.
* *
*/ */
class Catalog_remote extends Catalog { class Catalog_remote extends Catalog
{
private $version = '000001'; private $version = '000001';
private $type = 'remote'; private $type = 'remote';
private $description = 'Remote Ampache Catalog'; private $description = 'Remote Ampache Catalog';
/** /**
* get_description * get_description
* This returns the description of this catalog * This returns the description of this catalog
*/ */
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
/** /**
* get_type * get_type
* This returns the current catalog type * This returns the current catalog type
*/ */
public function get_type() { public function get_type()
{
return $this->type; return $this->type;
} // get_type } // get_type
/** /**
* get_create_help * get_create_help
* This returns hints on catalog creation * This returns hints on catalog creation
*/ */
public function get_create_help() { public function get_create_help()
{
return ""; return "";
} // get_create_help } // get_create_help
@ -76,12 +76,12 @@ class Catalog_remote extends Catalog {
* is_installed * is_installed
* This returns true or false if remote catalog is installed * This returns true or false if remote catalog is installed
*/ */
public function is_installed() { public function is_installed()
{
$sql = "DESCRIBE `catalog_remote`";
$db_results = Dba::query($sql);
$sql = "DESCRIBE `catalog_remote`"; return Dba::num_rows($db_results);
$db_results = Dba::query($sql);
return Dba::num_rows($db_results);
} // is_installed } // is_installed
@ -90,30 +90,30 @@ class Catalog_remote extends Catalog {
* install * install
* This function installs the remote catalog * This function installs the remote catalog
*/ */
public function install() { public function install()
{
$sql = "CREATE TABLE `catalog_remote` (`id` INT( 11 ) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY , ". $sql = "CREATE TABLE `catalog_remote` (`id` INT( 11 ) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY , ".
"`uri` VARCHAR( 255 ) COLLATE utf8_unicode_ci NOT NULL , " . "`uri` VARCHAR( 255 ) COLLATE utf8_unicode_ci NOT NULL , " .
"`username` VARCHAR( 255 ) COLLATE utf8_unicode_ci NOT NULL , " . "`username` VARCHAR( 255 ) COLLATE utf8_unicode_ci NOT NULL , " .
"`password` VARCHAR( 255 ) COLLATE utf8_unicode_ci NOT NULL , " . "`password` VARCHAR( 255 ) COLLATE utf8_unicode_ci NOT NULL , " .
"`catalog_id` INT( 11 ) NOT NULL" . "`catalog_id` INT( 11 ) NOT NULL" .
") 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::query($sql);
return true; return true;
} // install } // install
public function catalog_fields() {
public function catalog_fields()
{
$fields['uri'] = array('description' => T_('Uri'),'type'=>'textbox'); $fields['uri'] = array('description' => T_('Uri'),'type'=>'textbox');
$fields['username'] = array('description' => T_('Username'),'type'=>'textbox'); $fields['username'] = array('description' => T_('Username'),'type'=>'textbox');
$fields['password'] = array('description' => T_('Password'),'type'=>'password'); $fields['password'] = array('description' => T_('Password'),'type'=>'password');
return $fields; return $fields;
}
}
public $uri; public $uri;
public $username; public $username;
public $password; public $password;
@ -123,7 +123,8 @@ class Catalog_remote extends Catalog {
* *
* Catalog class constructor, pulls catalog information * Catalog class constructor, pulls catalog information
*/ */
public function __construct($catalog_id = null) { public function __construct($catalog_id = null)
{
if ($catalog_id) { if ($catalog_id) {
$this->id = intval($catalog_id); $this->id = intval($catalog_id);
$info = $this->get_info($catalog_id); $info = $this->get_info($catalog_id);
@ -141,23 +142,23 @@ class Catalog_remote extends Catalog {
* It checks to make sure its parameters is not already used before creating * It checks to make sure its parameters is not already used before creating
* the catalog. * the catalog.
*/ */
public static function create_type($catalog_id, $data) { public static function create_type($catalog_id, $data)
{
$uri = $data['uri']; $uri = $data['uri'];
$username = $data['username']; $username = $data['username'];
$password = $data['password']; $password = $data['password'];
if (substr($uri,0,7) != 'http://' && substr($uri,0,8) != 'https://') { if (substr($uri,0,7) != 'http://' && substr($uri,0,8) != 'https://') {
Error::add('general', T_('Error: Remote selected, but path is not a URL')); Error::add('general', T_('Error: Remote selected, but path is not a URL'));
return false; return false;
} }
if (!strlen($username) OR !strlen($password)) { if (!strlen($username) OR !strlen($password)) {
Error::add('general', T_('Error: Username and Password Required for Remote Catalogs')); Error::add('general', T_('Error: Username and Password Required for Remote Catalogs'));
return false; return false;
} }
$password = hash('sha256', $password); $password = hash('sha256', $password);
// Make sure this uri isn't already in use by an existing catalog // Make sure this uri isn't already in use by an existing catalog
$sql = 'SELECT `id` FROM `catalog_remote` WHERE `uri` = ?'; $sql = 'SELECT `id` FROM `catalog_remote` WHERE `uri` = ?';
$db_results = Dba::read($sql, array($uri)); $db_results = Dba::read($sql, array($uri));
@ -178,12 +179,12 @@ class Catalog_remote extends Catalog {
* this function adds new files to an * this function adds new files to an
* existing catalog * existing catalog
*/ */
public function add_to_catalog($options = null) { public function add_to_catalog($options = null)
{
UI::show_box_top(T_('Running Remote Update') . '. . .'); UI::show_box_top(T_('Running Remote Update') . '. . .');
$this->update_remote_catalog(); $this->update_remote_catalog();
UI::show_box_bottom(); UI::show_box_bottom();
return true; return true;
} // add_to_catalog } // add_to_catalog
@ -192,7 +193,8 @@ class Catalog_remote extends Catalog {
* *
* Connects to the remote catalog that we are. * Connects to the remote catalog that we are.
*/ */
public function connect() { public function connect()
{
try { try {
$remote_handle = new AmpacheApi(array( $remote_handle = new AmpacheApi(array(
'username' => $this->username, 'username' => $this->username,
@ -215,7 +217,7 @@ class Catalog_remote extends Catalog {
return false; return false;
} }
return $remote_handle; return $remote_handle;
} }
/** /**
@ -224,7 +226,8 @@ class Catalog_remote extends Catalog {
* Pulls the data from a remote catalog and adds any missing songs to the * Pulls the data from a remote catalog and adds any missing songs to the
* database. * database.
*/ */
public function update_remote_catalog($type = 0) { public function update_remote_catalog($type = 0)
{
$remote_handle = $this->connect(); $remote_handle = $this->connect();
if (!$remote_handle) { if (!$remote_handle) {
return false; return false;
@ -247,8 +250,7 @@ class Catalog_remote extends Catalog {
$current += $step; $current += $step;
try { try {
$songs = $remote_handle->send_command('songs', array('offset' => $start, 'limit' => $step)); $songs = $remote_handle->send_command('songs', array('offset' => $start, 'limit' => $step));
} } catch (Exception $e) {
catch (Exception $e) {
Error::add('general',$e->getMessage()); Error::add('general',$e->getMessage());
Error::display('general'); Error::display('general');
flush(); flush();
@ -258,8 +260,7 @@ class Catalog_remote extends Catalog {
foreach ($songs as $data) { foreach ($songs as $data) {
if ($this->check_remote_song($data['song'])) { if ($this->check_remote_song($data['song'])) {
debug_event('remote_catalog', 'Skipping existing song ' . $data['song']['url'], 5); debug_event('remote_catalog', 'Skipping existing song ' . $data['song']['url'], 5);
} } else {
else {
$data['song']['catalog'] = $this->id; $data['song']['catalog'] = $this->id;
$data['song']['file'] = preg_replace('/ssid=.*?&/', '', $data['song']['url']); $data['song']['file'] = preg_replace('/ssid=.*?&/', '', $data['song']['url']);
if (!Song::insert($data['song'])) { if (!Song::insert($data['song'])) {
@ -281,17 +282,19 @@ class Catalog_remote extends Catalog {
return true; return true;
} }
public function verify_catalog_proc() { public function verify_catalog_proc()
{
return array('total' => 0, 'updated' => 0); return array('total' => 0, 'updated' => 0);
} }
/** /**
* clean_catalog_proc * clean_catalog_proc
* *
* Removes remote songs that no longer exist. * Removes remote songs that no longer exist.
*/ */
public function clean_catalog_proc() { public function clean_catalog_proc()
{
$remote_handle = $this->connect(); $remote_handle = $this->connect();
if (!$remote_handle) { if (!$remote_handle) {
debug_event('remote-clean', 'Remote login failed', 1, 'ampache-catalog'); debug_event('remote-clean', 'Remote login failed', 1, 'ampache-catalog');
@ -306,15 +309,13 @@ class Catalog_remote extends Catalog {
debug_event('remote-clean', 'Starting work on ' . $row['file'] . '(' . $row['id'] . ')', 5, 'ampache-catalog'); debug_event('remote-clean', 'Starting work on ' . $row['file'] . '(' . $row['id'] . ')', 5, 'ampache-catalog');
try { try {
$song = $remote_handle->send_command('url_to_song', array('url' => $row['file'])); $song = $remote_handle->send_command('url_to_song', array('url' => $row['file']));
} } catch (Exception $e) {
catch (Exception $e) {
// FIXME: What to do, what to do // FIXME: What to do, what to do
} }
if (count($song) == 1) { if (count($song) == 1) {
debug_event('remote-clean', 'keeping song', 5, 'ampache-catalog'); debug_event('remote-clean', 'keeping song', 5, 'ampache-catalog');
} } else {
else {
debug_event('remote-clean', 'removing song', 5, 'ampache-catalog'); debug_event('remote-clean', 'removing song', 5, 'ampache-catalog');
$dead++; $dead++;
Dba::write('DELETE FROM `song` WHERE `id` = ?', array($row['id'])); Dba::write('DELETE FROM `song` WHERE `id` = ?', array($row['id']));
@ -330,7 +331,8 @@ class Catalog_remote extends Catalog {
* checks to see if a remote song exists in the database or not * checks to see if a remote song exists in the database or not
* if it find a song it returns the UID * if it find a song it returns the UID
*/ */
public function check_remote_song($song) { public function check_remote_song($song)
{
$url = preg_replace('/ssid=.*&/', '', $song['url']); $url = preg_replace('/ssid=.*&/', '', $song['url']);
$sql = 'SELECT `id` FROM `song` WHERE `file` = ?'; $sql = 'SELECT `id` FROM `song` WHERE `file` = ?';
@ -342,25 +344,27 @@ class Catalog_remote extends Catalog {
return false; return false;
} }
public function get_rel_path($file_path) { public function get_rel_path($file_path)
{
$info = $this->_get_info(); $info = $this->_get_info();
$catalog_path = rtrim($info->uri, "/"); $catalog_path = rtrim($info->uri, "/");
return( str_replace( $catalog_path . "/", "", $file_path ) ); return( str_replace( $catalog_path . "/", "", $file_path ) );
} }
/** /**
* format * format
* *
* This makes the object human-readable. * This makes the object human-readable.
*/ */
public function format() { public function format()
{
parent::format(); parent::format();
$this->f_info = UI::truncate($this->uri, Config::get('ellipse_threshold_title')); $this->f_info = UI::truncate($this->uri, Config::get('ellipse_threshold_title'));
} }
public function prepare_media($media) { public function prepare_media($media)
{
$remote_handle = $this->connect(); $remote_handle = $this->connect();
// If we don't get anything back we failed and should bail now // If we don't get anything back we failed and should bail now
@ -373,11 +377,9 @@ class Catalog_remote extends Catalog {
$url = $media->file . '&ssid=' . $handshake['auth']; $url = $media->file . '&ssid=' . $handshake['auth'];
header('Location: ' . $url); header('Location: ' . $url);
debug_event('play', 'Started remote stream - ' . $url, 5); debug_event('play', 'Started remote stream - ' . $url, 5);
return null; return null;
} }
} // end of catalog class } // end of catalog class
?>

View file

@ -26,48 +26,48 @@
* This class handles all actual work in regards to remote Subsonic catalogs. * This class handles all actual work in regards to remote Subsonic catalogs.
* *
*/ */
class Catalog_subsonic extends Catalog { class Catalog_subsonic extends Catalog
{
private $version = '000001'; private $version = '000001';
private $type = 'subsonic'; private $type = 'subsonic';
private $description = 'Remote Subsonic Catalog'; private $description = 'Remote Subsonic Catalog';
/** /**
* get_description * get_description
* This returns the description of this catalog * This returns the description of this catalog
*/ */
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
/** /**
* get_type * get_type
* This returns the current catalog type * This returns the current catalog type
*/ */
public function get_type() { public function get_type()
{
return $this->type; return $this->type;
} // get_type } // get_type
/** /**
* get_create_help * get_create_help
* This returns hints on catalog creation * This returns hints on catalog creation
*/ */
public function get_create_help() { public function get_create_help()
{
return ""; return "";
} // get_create_help } // get_create_help
@ -76,12 +76,12 @@ class Catalog_subsonic extends Catalog {
* is_installed * is_installed
* This returns true or false if remote catalog is installed * This returns true or false if remote catalog is installed
*/ */
public function is_installed() { public function is_installed()
{
$sql = "DESCRIBE `catalog_subsonic`";
$db_results = Dba::query($sql);
$sql = "DESCRIBE `catalog_subsonic`"; return Dba::num_rows($db_results);
$db_results = Dba::query($sql);
return Dba::num_rows($db_results);
} // is_installed } // is_installed
@ -90,30 +90,30 @@ class Catalog_subsonic extends Catalog {
* install * install
* This function installs the remote catalog * This function installs the remote catalog
*/ */
public function install() { public function install()
{
$sql = "CREATE TABLE `catalog_subsonic` (`id` INT( 11 ) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY , ". $sql = "CREATE TABLE `catalog_subsonic` (`id` INT( 11 ) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY , ".
"`uri` VARCHAR( 255 ) COLLATE utf8_unicode_ci NOT NULL , " . "`uri` VARCHAR( 255 ) COLLATE utf8_unicode_ci NOT NULL , " .
"`username` VARCHAR( 255 ) COLLATE utf8_unicode_ci NOT NULL , " . "`username` VARCHAR( 255 ) COLLATE utf8_unicode_ci NOT NULL , " .
"`password` VARCHAR( 255 ) COLLATE utf8_unicode_ci NOT NULL , " . "`password` VARCHAR( 255 ) COLLATE utf8_unicode_ci NOT NULL , " .
"`catalog_id` INT( 11 ) NOT NULL" . "`catalog_id` INT( 11 ) NOT NULL" .
") 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::query($sql);
return true; return true;
} // install } // install
public function catalog_fields() {
public function catalog_fields()
{
$fields['uri'] = array('description' => T_('Uri'),'type'=>'textbox'); $fields['uri'] = array('description' => T_('Uri'),'type'=>'textbox');
$fields['username'] = array('description' => T_('Username'),'type'=>'textbox'); $fields['username'] = array('description' => T_('Username'),'type'=>'textbox');
$fields['password'] = array('description' => T_('Password'),'type'=>'password'); $fields['password'] = array('description' => T_('Password'),'type'=>'password');
return $fields; return $fields;
}
}
public $uri; public $uri;
public $username; public $username;
public $password; public $password;
@ -123,7 +123,8 @@ class Catalog_subsonic extends Catalog {
* *
* Catalog class constructor, pulls catalog information * Catalog class constructor, pulls catalog information
*/ */
public function __construct($catalog_id = null) { public function __construct($catalog_id = null)
{
if ($catalog_id) { if ($catalog_id) {
$this->id = intval($catalog_id); $this->id = intval($catalog_id);
$info = $this->get_info($catalog_id); $info = $this->get_info($catalog_id);
@ -132,7 +133,7 @@ class Catalog_subsonic extends Catalog {
$this->$key = $value; $this->$key = $value;
} }
} }
require_once Config::get('prefix') . '/modules/subsonic/subsonic.client.php'; require_once Config::get('prefix') . '/modules/subsonic/subsonic.client.php';
} }
@ -143,22 +144,22 @@ class Catalog_subsonic extends Catalog {
* It checks to make sure its parameters is not already used before creating * It checks to make sure its parameters is not already used before creating
* the catalog. * the catalog.
*/ */
public static function create_type($catalog_id, $data) { public static function create_type($catalog_id, $data)
{
$uri = $data['uri']; $uri = $data['uri'];
$username = $data['username']; $username = $data['username'];
$password = $data['password']; $password = $data['password'];
if (substr($uri,0,7) != 'http://' && substr($uri,0,8) != 'https://') { if (substr($uri,0,7) != 'http://' && substr($uri,0,8) != 'https://') {
Error::add('general', T_('Error: Subsonic selected, but path is not a URL')); Error::add('general', T_('Error: Subsonic selected, but path is not a URL'));
return false; return false;
} }
if (!strlen($username) OR !strlen($password)) { if (!strlen($username) OR !strlen($password)) {
Error::add('general', T_('Error: Username and Password Required for Subsonic Catalogs')); Error::add('general', T_('Error: Username and Password Required for Subsonic Catalogs'));
return false; return false;
} }
// Make sure this uri isn't already in use by an existing catalog // Make sure this uri isn't already in use by an existing catalog
$sql = 'SELECT `id` FROM `catalog_subsonic` WHERE `uri` = ?'; $sql = 'SELECT `id` FROM `catalog_subsonic` WHERE `uri` = ?';
$db_results = Dba::read($sql, array($uri)); $db_results = Dba::read($sql, array($uri));
@ -179,18 +180,20 @@ class Catalog_subsonic extends Catalog {
* this function adds new files to an * this function adds new files to an
* existing catalog * existing catalog
*/ */
public function add_to_catalog($options = null) { public function add_to_catalog($options = null)
{
// Prevent the script from timing out // Prevent the script from timing out
set_time_limit(0); set_time_limit(0);
UI::show_box_top(T_('Running Subsonic Remote Update') . '. . .'); UI::show_box_top(T_('Running Subsonic Remote Update') . '. . .');
$this->update_remote_catalog(); $this->update_remote_catalog();
UI::show_box_bottom(); UI::show_box_bottom();
return true; return true;
} // add_to_catalog } // add_to_catalog
public function createClient() { public function createClient()
{
return (new SubsonicClient($this->username, $this->password, $this->uri, null)); return (new SubsonicClient($this->username, $this->password, $this->uri, null));
} }
@ -200,7 +203,8 @@ class Catalog_subsonic extends Catalog {
* Pulls the data from a remote catalog and adds any missing songs to the * Pulls the data from a remote catalog and adds any missing songs to the
* database. * database.
*/ */
public function update_remote_catalog() { public function update_remote_catalog()
{
$subsonic = $this->createClient(); $subsonic = $this->createClient();
$songsadded = 0; $songsadded = 0;
@ -211,7 +215,7 @@ class Catalog_subsonic extends Catalog {
foreach ($index['artist'] as $artist) { foreach ($index['artist'] as $artist) {
// Get albums for artist // Get albums for artist
$albums = $subsonic->getMusicDirectory(array('id' => $artist['id'])); $albums = $subsonic->getMusicDirectory(array('id' => $artist['id']));
if ($albums['success']) { if ($albums['success']) {
foreach ($albums['data']['directory']['child'] as $album) { foreach ($albums['data']['directory']['child'] as $album) {
if (is_array($album)) { if (is_array($album)) {
@ -233,8 +237,7 @@ class Catalog_subsonic extends Catalog {
$data['file'] = $this->uri . '/rest/stream.view?id=' . $song['id'] . '&filename=' . urlencode($song['path']); $data['file'] = $this->uri . '/rest/stream.view?id=' . $song['id'] . '&filename=' . urlencode($song['path']);
if ($this->check_remote_song($data)) { if ($this->check_remote_song($data)) {
debug_event('subsonic_catalog', 'Skipping existing song ' . $data['path'], 5); debug_event('subsonic_catalog', 'Skipping existing song ' . $data['path'], 5);
} } else {
else {
$data['catalog'] = $this->id; $data['catalog'] = $this->id;
debug_event('subsonic_catalog', 'Adding song ' . $song['path'], 5, 'ampache-catalog'); debug_event('subsonic_catalog', 'Adding song ' . $song['path'], 5, 'ampache-catalog');
if (!Song::insert($data)) { if (!Song::insert($data)) {
@ -274,17 +277,19 @@ class Catalog_subsonic extends Catalog {
return true; return true;
} }
public function verify_catalog_proc() { public function verify_catalog_proc()
{
return array('total' => 0, 'updated' => 0); return array('total' => 0, 'updated' => 0);
} }
/** /**
* clean_catalog_proc * clean_catalog_proc
* *
* Removes subsonic songs that no longer exist. * Removes subsonic songs that no longer exist.
*/ */
public function clean_catalog_proc() { public function clean_catalog_proc()
{
$subsonic = $this->createClient(); $subsonic = $this->createClient();
$dead = 0; $dead = 0;
@ -300,15 +305,13 @@ class Catalog_subsonic extends Catalog {
if (!$song['success']) { if (!$song['success']) {
$remove = true; $remove = true;
} }
} } catch (Exception $e) {
catch (Exception $e) {
debug_event('subsonic-clean', 'Clean error: ' . $e->getMessage(), 5, 'ampache-catalog'); debug_event('subsonic-clean', 'Clean error: ' . $e->getMessage(), 5, 'ampache-catalog');
} }
if (!$remove) { if (!$remove) {
debug_event('subsonic-clean', 'keeping song', 5, 'ampache-catalog'); debug_event('subsonic-clean', 'keeping song', 5, 'ampache-catalog');
} } else {
else {
debug_event('subsonic-clean', 'removing song', 5, 'ampache-catalog'); debug_event('subsonic-clean', 'removing song', 5, 'ampache-catalog');
$dead++; $dead++;
Dba::write('DELETE FROM `song` WHERE `id` = ?', array($row['id'])); Dba::write('DELETE FROM `song` WHERE `id` = ?', array($row['id']));
@ -324,7 +327,8 @@ class Catalog_subsonic extends Catalog {
* checks to see if a remote song exists in the database or not * checks to see if a remote song exists in the database or not
* if it find a song it returns the UID * if it find a song it returns the UID
*/ */
public function check_remote_song($song) { public function check_remote_song($song)
{
$url = $song['file']; $url = $song['file'];
$sql = 'SELECT `id` FROM `song` WHERE `file` = ?'; $sql = 'SELECT `id` FROM `song` WHERE `file` = ?';
@ -336,14 +340,16 @@ class Catalog_subsonic extends Catalog {
return false; return false;
} }
public function get_rel_path($file_path) { public function get_rel_path($file_path)
{
$info = $this->_get_info(); $info = $this->_get_info();
$catalog_path = rtrim($info->uri, "/"); $catalog_path = rtrim($info->uri, "/");
return( str_replace( $catalog_path . "/", "", $file_path ) ); return( str_replace( $catalog_path . "/", "", $file_path ) );
} }
public function url_to_songid($url) { public function url_to_songid($url)
{
$id = 0; $id = 0;
preg_match('/\?id=([0-9]*)&/', $url, $matches); preg_match('/\?id=([0-9]*)&/', $url, $matches);
if (count($matches)) { if (count($matches)) {
@ -351,28 +357,27 @@ class Catalog_subsonic extends Catalog {
} }
return $id; return $id;
} }
/** /**
* format * format
* *
* This makes the object human-readable. * This makes the object human-readable.
*/ */
public function format() { public function format()
{
parent::format(); parent::format();
$this->f_info = UI::truncate($this->uri, Config::get('ellipse_threshold_title')); $this->f_info = UI::truncate($this->uri, Config::get('ellipse_threshold_title'));
} }
public function prepare_media($media) { public function prepare_media($media)
{
$subsonic = $this->createClient(); $subsonic = $this->createClient();
$url = $subsonic->parameterize($media->file . '&'); $url = $subsonic->parameterize($media->file . '&');
header('Location: ' . $url); header('Location: ' . $url);
debug_event('play', 'Started remote stream - ' . $url, 5); debug_event('play', 'Started remote stream - ' . $url, 5);
return null; return null;
} }
} // end of catalog class } // end of catalog class
?>

View file

@ -28,8 +28,8 @@
* *
*/ */
class AmpacheHttpq extends localplay_controller { class AmpacheHttpq extends localplay_controller
{
/* Variables */ /* Variables */
private $version = '000002'; private $version = '000002';
private $description = "Controls an httpQ instance, requires Ampache's httpQ version"; private $description = "Controls an httpQ instance, requires Ampache's httpQ version";
@ -42,8 +42,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';
@ -53,8 +53,8 @@ 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
@ -63,8 +63,8 @@ class AmpacheHttpq extends localplay_controller {
* 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
@ -73,8 +73,8 @@ class AmpacheHttpq extends localplay_controller {
* is_installed * is_installed
* This returns true or false if this controller is installed * This returns true or false if this controller is installed
*/ */
public function is_installed() { public function is_installed()
{
$sql = "DESCRIBE `localplay_httpq`"; $sql = "DESCRIBE `localplay_httpq`";
$db_results = Dba::read($sql); $db_results = Dba::read($sql);
@ -87,8 +87,8 @@ class AmpacheHttpq extends localplay_controller {
* install * install
* This function installs the controller * This function installs the 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, " .
@ -111,8 +111,8 @@ class AmpacheHttpq 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_httpq`"; $sql = "DROP TABLE `localplay_httpq`";
$db_results = Dba::write($sql); $db_results = Dba::write($sql);
@ -127,8 +127,8 @@ class AmpacheHttpq extends localplay_controller {
* add_instance * add_instance
* This takes keyed data and inserts a new httpQ instance * This takes keyed data and inserts a new httpQ instance
*/ */
public function add_instance($data) { public function add_instance($data)
{
$name = Dba::escape($data['name']); $name = Dba::escape($data['name']);
$host = Dba::escape($data['host']); $host = Dba::escape($data['host']);
$port = Dba::escape($data['port']); $port = Dba::escape($data['port']);
@ -148,8 +148,8 @@ class AmpacheHttpq 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);
$sql = "DELETE FROM `localplay_httpq` WHERE `id`='$uid'"; $sql = "DELETE FROM `localplay_httpq` WHERE `id`='$uid'";
@ -164,8 +164,8 @@ class AmpacheHttpq extends localplay_controller {
* This returns a keyed array of the instance information with * This returns a keyed 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::read($sql); $db_results = Dba::read($sql);
@ -183,8 +183,8 @@ 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']);
@ -203,8 +203,8 @@ class AmpacheHttpq extends localplay_controller {
* This returns a keyed array of [NAME]=>array([DESCRIPTION]=>VALUE,[TYPE]=>VALUE) for the * This returns a keyed 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' => T_('Instance Name'),'type'=>'textbox'); $fields['name'] = array('description' => T_('Instance Name'),'type'=>'textbox');
$fields['host'] = array('description' => T_('Hostname'),'type'=>'textbox'); $fields['host'] = array('description' => T_('Hostname'),'type'=>'textbox');
$fields['port'] = array('description' => T_('Port'),'type'=>'textbox'); $fields['port'] = array('description' => T_('Port'),'type'=>'textbox');
@ -218,8 +218,8 @@ class AmpacheHttpq extends localplay_controller {
* get_instance * get_instance
* This returns a single instance and all its variables * This returns a single instance and all its 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);
@ -236,8 +236,8 @@ class AmpacheHttpq 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;
@ -257,21 +257,21 @@ class AmpacheHttpq extends localplay_controller {
* 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_url * add_url
* This is the new hotness * This is the new hotness
*/ */
public function add_url(Stream_URL $url) { public function add_url(Stream_URL $url)
{
if (is_null($this->_httpq->add($url->title, $url->url))) { if (is_null($this->_httpq->add($url->title, $url->url))) {
debug_event('httpq', 'add_url failed to add ' . $url, 1); debug_event('httpq', 'add_url failed to add ' . $url, 1);
return false; return false;
} }
return true; return true;
} }
@ -280,8 +280,8 @@ class AmpacheHttpq extends localplay_controller {
* This must take an ID (as returned by our get function) * This must take an ID (as returned by our get function)
* and delete it from httpQ * and delete it 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', 'Unable to delete ' . $object_id . ' from httpQ', 1); debug_event('httpq', 'Unable to delete ' . $object_id . ' from httpQ', 1);
return false; return false;
@ -294,8 +294,8 @@ class AmpacheHttpq extends localplay_controller {
/** /**
* clear_playlist * clear_playlist
*/ */
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!
@ -310,7 +310,8 @@ 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,
// so doublecheck its state // so doublecheck its state
if ($this->_httpq->state() == 'play') { if ($this->_httpq->state() == 'play') {
@ -326,8 +327,8 @@ 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;
@ -337,8 +338,8 @@ 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;
@ -347,8 +348,8 @@ class AmpacheHttpq extends localplay_controller {
/** /**
* 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;
@ -357,8 +358,8 @@ class AmpacheHttpq extends localplay_controller {
/** /**
* This tells httpQ to decrease the volume by Winamp's default amount * This tells httpQ to decrease the volume by Winamp's 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;
@ -368,8 +369,8 @@ class AmpacheHttpq extends localplay_controller {
* 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;
@ -380,8 +381,8 @@ 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;
@ -392,8 +393,8 @@ class AmpacheHttpq extends localplay_controller {
* 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;
@ -404,8 +405,8 @@ class AmpacheHttpq extends localplay_controller {
* This tells httpQ to set the volume to the specified amount this * This tells httpQ to set the volume to the specified amount this
* is 0-100 * is 0-100
*/ */
public function volume($volume) { public function volume($volume)
{
if (is_null($this->_httpq->set_volume($volume))) { return false; } if (is_null($this->_httpq->set_volume($volume))) { return false; }
return true; return true;
@ -416,8 +417,8 @@ class AmpacheHttpq extends localplay_controller {
* This tells httpQ to set the repeating the playlist (i.e. loop) to * This tells httpQ to set the repeating the playlist (i.e. loop) to
* either on or off * 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;
@ -428,8 +429,8 @@ class AmpacheHttpq extends localplay_controller {
* This tells httpQ to turn on or off the playing of songs from the * This tells httpQ to turn on or off the playing of songs from the
* playlist in random order * playlist in random order
*/ */
public function random($onoff) { public function random($onoff)
{
if (is_null($this->_httpq->random($onoff))) { return false; } if (is_null($this->_httpq->random($onoff))) { return false; }
return true; return true;
@ -441,8 +442,8 @@ class AmpacheHttpq extends localplay_controller {
* The songs that httpQ currently has in its playlist. This must be * The songs that httpQ currently has in its 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();
@ -521,8 +522,8 @@ 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();
$array['volume'] = $this->_httpq->get_volume(); $array['volume'] = $this->_httpq->get_volume();
@ -536,8 +537,7 @@ class AmpacheHttpq extends localplay_controller {
$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']);
} }
@ -551,8 +551,8 @@ 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']);
@ -564,5 +564,3 @@ class AmpacheHttpq extends localplay_controller {
} // connect } // connect
} //end of AmpacheHttpq } //end of AmpacheHttpq
?>

View file

@ -27,12 +27,12 @@
* the MPD class and the Ampache Localplay class * the MPD class and the Ampache Localplay class
* *
*/ */
class AmpacheMpd extends localplay_controller { class AmpacheMpd extends localplay_controller
{
/* Variables */ /* Variables */
private $version = '000003'; private $version = '000003';
private $description = 'Controls an instance of MPD'; private $description = 'Controls an instance of MPD';
private $_add_count = 0; private $_add_count = 0;
/* Constructed variables */ /* Constructed variables */
@ -43,8 +43,8 @@ class AmpacheMpd 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/mpd/mpd.class.php'; require_once Config::get('prefix') . '/modules/mpd/mpd.class.php';
@ -54,8 +54,8 @@ class AmpacheMpd 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
@ -64,8 +64,8 @@ class AmpacheMpd extends localplay_controller {
* 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,8 +74,8 @@ class AmpacheMpd 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_mpd`"; $sql = "DESCRIBE `localplay_mpd`";
$db_results = Dba::read($sql); $db_results = Dba::read($sql);
@ -87,8 +87,8 @@ class AmpacheMpd 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_mpd` ( `id` INT( 11 ) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY , " . $sql = "CREATE TABLE `localplay_mpd` ( `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 , " .
@ -112,8 +112,8 @@ class AmpacheMpd 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_mpd`"; $sql = "DROP TABLE `localplay_mpd`";
$db_results = Dba::write($sql); $db_results = Dba::write($sql);
@ -127,8 +127,8 @@ class AmpacheMpd 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':
@ -157,8 +157,8 @@ class AmpacheMpd 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!
@ -174,8 +174,8 @@ class AmpacheMpd extends localplay_controller {
* 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_mpd` ORDER BY `name`"; $sql = "SELECT * FROM `localplay_mpd` ORDER BY `name`";
$db_results = Dba::read($sql); $db_results = Dba::read($sql);
@ -194,8 +194,8 @@ class AmpacheMpd 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('mpd_active'); $instance = $instance ? $instance : Config::get('mpd_active');
$instance = Dba::escape($instance); $instance = Dba::escape($instance);
@ -212,8 +212,8 @@ class AmpacheMpd 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);
$host = $data['host'] ? Dba::escape($data['host']) : '127.0.0.1'; $host = $data['host'] ? Dba::escape($data['host']) : '127.0.0.1';
$port = $data['port'] ? Dba::escape($data['port']) : '6600'; $port = $data['port'] ? Dba::escape($data['port']) : '6600';
@ -232,8 +232,8 @@ class AmpacheMpd 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' => T_('Instance Name'),'type'=>'textbox'); $fields['name'] = array('description' => T_('Instance Name'),'type'=>'textbox');
$fields['host'] = array('description' => T_('Hostname'),'type'=>'textbox'); $fields['host'] = array('description' => T_('Hostname'),'type'=>'textbox');
$fields['port'] = array('description' => T_('Port'),'type'=>'textbox'); $fields['port'] = array('description' => T_('Port'),'type'=>'textbox');
@ -247,8 +247,8 @@ class AmpacheMpd 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;
@ -268,16 +268,16 @@ class AmpacheMpd extends localplay_controller {
* 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_url * add_url
* This is the new hotness * This is the new hotness
*/ */
public function add_url(Stream_URL $url) { public function add_url(Stream_URL $url)
{
// If we haven't added anything then maybe we should clear the // If we haven't added anything then maybe we should clear the
// playlist. // playlist.
if ($this->_add_count < 1) { if ($this->_add_count < 1) {
@ -301,7 +301,8 @@ class AmpacheMpd extends localplay_controller {
* This must take a single ID (as returned by the get function) * This must take a single ID (as returned by the get function)
* 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 $this->_mpd->PLRemove($object_id); return $this->_mpd->PLRemove($object_id);
} // delete_track } // delete_track
@ -309,7 +310,8 @@ class AmpacheMpd extends localplay_controller {
* clear_playlist * clear_playlist
* This deletes the entire MPD playlist... nuff said * This deletes the entire MPD playlist... nuff said
*/ */
public function clear_playlist() { public function clear_playlist()
{
return $this->_mpd->PLClear(); return $this->_mpd->PLClear();
} // clear_playlist } // clear_playlist
@ -318,7 +320,8 @@ class AmpacheMpd 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()
{
return $this->_mpd->Play(); return $this->_mpd->Play();
} // play } // play
@ -327,7 +330,8 @@ class AmpacheMpd extends localplay_controller {
* This just tells MPD to stop playing, it does not take * This just tells MPD to stop playing, it does not take
* any arguments * any arguments
*/ */
public function stop() { public function stop()
{
return $this->_mpd->Stop(); return $this->_mpd->Stop();
} // stop } // stop
@ -335,8 +339,8 @@ class AmpacheMpd extends localplay_controller {
* skip * skip
* This tells MPD to skip to the specified song * This tells MPD to skip to the specified song
*/ */
public function skip($song) { public function skip($song)
{
if (!$this->_mpd->SkipTo($song)) { return false; } if (!$this->_mpd->SkipTo($song)) { return false; }
sleep(2); sleep(2);
$this->stop(); $this->stop();
@ -349,14 +353,16 @@ class AmpacheMpd extends localplay_controller {
/** /**
* 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 $this->_mpd->AdjustVolume('5'); return $this->_mpd->AdjustVolume('5');
} // volume_up } // volume_up
/** /**
* This tells MPD to decrease the volume by 5 * This tells MPD to decrease the volume by 5
*/ */
public function volume_down() { public function volume_down()
{
return $this->_mpd->AdjustVolume('-5'); return $this->_mpd->AdjustVolume('-5');
} // volume_down } // volume_down
@ -364,7 +370,8 @@ class AmpacheMpd extends localplay_controller {
* 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()
{
return $this->_mpd->Next(); return $this->_mpd->Next();
} // next } // next
@ -372,7 +379,8 @@ class AmpacheMpd 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 $this->_mpd->Previous(); return $this->_mpd->Previous();
} // prev } // prev
@ -380,7 +388,8 @@ class AmpacheMpd extends localplay_controller {
* pause * pause
* This tells MPD to pause the current song * This tells MPD to pause the current song
*/ */
public function pause() { public function pause()
{
return $this->_mpd->Pause(); return $this->_mpd->Pause();
} // pause } // pause
@ -389,7 +398,8 @@ class AmpacheMpd extends localplay_controller {
* volume * volume
* This tells MPD to set the volume to the parameter * This tells MPD to set the volume to the parameter
*/ */
public function volume($volume) { public function volume($volume)
{
return $this->_mpd->SetVolume($volume); return $this->_mpd->SetVolume($volume);
} // volume } // volume
@ -398,7 +408,8 @@ class AmpacheMpd extends localplay_controller {
* This tells MPD to set the repeating the playlist (i.e. loop) to either * This tells MPD to set the repeating the playlist (i.e. loop) to either
* on or off. * on or off.
*/ */
public function repeat($state) { public function repeat($state)
{
return $this->_mpd->SetRepeat($state); return $this->_mpd->SetRepeat($state);
} // repeat } // repeat
@ -407,7 +418,8 @@ class AmpacheMpd extends localplay_controller {
* This tells MPD to turn on or off the playing of songs from the * This tells MPD to turn on or off the playing of songs from the
* playlist in random order. * playlist in random order.
*/ */
public function random($onoff) { public function random($onoff)
{
return $this->_mpd->SetRandom($onoff); return $this->_mpd->SetRandom($onoff);
} // random } // random
@ -415,7 +427,8 @@ class AmpacheMpd extends localplay_controller {
* move * move
* This tells MPD to move a song * This tells MPD to move a song
*/ */
public function move($source, $destination) { public function move($source, $destination)
{
return $this->_mpd->PLMoveTrack($source, $destination); return $this->_mpd->PLMoveTrack($source, $destination);
} // move } // move
@ -425,7 +438,8 @@ class AmpacheMpd extends localplay_controller {
* the songs that MPD currently has in its playlist. This must be * the songs that MPD currently has in its playlist. This must be
* done in a standardized fashion * done in a standardized fashion
*/ */
public function get() { public function get()
{
// If we don't have the playlist yet, pull it // If we don't have the playlist yet, pull it
if (!isset($this->_mpd->playlist)) { if (!isset($this->_mpd->playlist)) {
$this->_mpd->RefreshInfo(); $this->_mpd->RefreshInfo();
@ -509,8 +523,8 @@ class AmpacheMpd extends localplay_controller {
* This returns bool/int values for features, loop, repeat and any other * This returns bool/int values for features, loop, repeat and any other
* features that this localplay method supports. * features that this localplay method supports.
*/ */
public function status() { public function status()
{
$track = $this->_mpd->status['song']; $track = $this->_mpd->status['song'];
/* Construct the Array */ /* Construct the Array */
@ -536,8 +550,8 @@ class AmpacheMpd 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()
{
// Look at the current instance and pull the options for said instance // Look at the current instance and pull the options for said instance
$options = self::get_instance(); $options = self::get_instance();
$this->_mpd = new mpd($options['host'], $options['port'], $options['password'], 'debug_event'); $this->_mpd = new mpd($options['host'], $options['port'], $options['password'], 'debug_event');
@ -549,5 +563,3 @@ class AmpacheMpd extends localplay_controller {
} // connect } // connect
} //end of AmpacheMpd } //end of AmpacheMpd
?>

View file

@ -16,7 +16,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,12 +27,12 @@
* a VLC Instance * a VLC Instance
* *
*/ */
class AmpacheVlc extends localplay_controller { class AmpacheVlc extends localplay_controller
{
/* Variables */ /* Variables */
private $version = 'Beta 0.2'; private $version = 'Beta 0.2';
private $description = 'Controls a Vlc instance'; private $description = 'Controls a Vlc instance';
/* Constructed variables */ /* Constructed variables */
private $_vlc; private $_vlc;
@ -42,30 +42,30 @@ class AmpacheVlc 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/vlc/vlcplayer.class.php'; require_once Config::get('prefix') . '/modules/vlc/vlcplayer.class.php';
} // Constructor } // Constructor
/** /**
* 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
@ -73,12 +73,12 @@ class AmpacheVlc extends localplay_controller {
* is_installed * is_installed
* This returns true or false if vlc controller is installed * This returns true or false if vlc controller is installed
*/ */
public function is_installed() { public function is_installed()
{
$sql = "DESCRIBE `localplay_vlc`";
$db_results = Dba::query($sql);
$sql = "DESCRIBE `localplay_vlc`"; return Dba::num_rows($db_results);
$db_results = Dba::query($sql);
return Dba::num_rows($db_results);
} // is_installed } // is_installed
@ -87,39 +87,39 @@ class AmpacheVlc extends localplay_controller {
* install * install
* This function installs the VLC localplay controller * This function installs the VLC localplay controller
*/ */
public function install() { public function install()
{
$sql = "CREATE TABLE `localplay_vlc` (`id` INT( 11 ) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY , ". $sql = "CREATE TABLE `localplay_vlc` (`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::query($sql);
// Add an internal preference for the users current active instance // Add an internal preference for the users current active instance
Preference::insert('vlc_active','VLC Active Instance','0','25','integer','internal'); Preference::insert('vlc_active','VLC 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_vlc`";
$db_results = Dba::query($sql);
$sql = "DROP TABLE `localplay_vlc`"; // Remove the pref we added for this
$db_results = Dba::query($sql); Preference::delete('vlc_active');
// Remove the pref we added for this return true;
Preference::delete('vlc_active');
return true;
} // uninstall } // uninstall
@ -127,58 +127,58 @@ class AmpacheVlc extends localplay_controller {
* add_instance * add_instance
* This takes key'd data and inserts a new vlc instance * This takes key'd data and inserts a new vlc instance
*/ */
public function add_instance($data) { public function add_instance($data)
{
$sql = "INSERT INTO `localplay_vlc` (`name`,`host`,`port`,`password`,`owner`) VALUES (?, ?, ?, ?, ?)";
$db_results = Dba::query($sql, array($data['name'], $data['host'], $data['port'], $data['password'], $GLOBALS['user']->id));
$sql = "INSERT INTO `localplay_vlc` (`name`,`host`,`port`,`password`,`owner`) VALUES (?, ?, ?, ?, ?)"; return $db_results;
$db_results = Dba::query($sql, array($data['name'], $data['host'], $data['port'], $data['password'], $GLOBALS['user']->id));
return $db_results;
} // add_instance } // add_instance
/** /**
* 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)
{
$sql = "DELETE FROM `localplay_vlc` WHERE `id` = ?"; $sql = "DELETE FROM `localplay_vlc` WHERE `id` = ?";
$db_results = Dba::query($sql, array($uid)); $db_results = Dba::query($sql, array($uid));
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_vlc` ORDER BY `name`";
$db_results = Dba::query($sql);
$sql = "SELECT * FROM `localplay_vlc` ORDER BY `name`"; $results = array();
$db_results = Dba::query($sql);
$results = array(); while ($row = Dba::fetch_assoc($db_results)) {
$results[$row['id']] = $row['name'];
}
return $results;
while ($row = Dba::fetch_assoc($db_results)) {
$results[$row['id']] = $row['name'];
}
return $results;
} // get_instances } // get_instances
/** /**
* 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)
{
$sql = "UPDATE `localplay_vlc` SET `host` = ?, `port` = ?, `name` = ?, `password` = ? WHERE `id` = ?"; $sql = "UPDATE `localplay_vlc` SET `host` = ?, `port` = ?, `name` = ?, `password` = ? WHERE `id` = ?";
$db_results = Dba::query($sql, array($data['host'], $data['port'], $data['name'], $data['password'], $uid)); $db_results = Dba::query($sql, array($data['host'], $data['port'], $data['name'], $data['password'], $uid));
return true; return true;
} // update_instance } // update_instance
@ -187,31 +187,31 @@ class AmpacheVlc 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' => T_('Instance Name'),'type'=>'textbox'); $fields['name'] = array('description' => T_('Instance Name'),'type'=>'textbox');
$fields['host'] = array('description' => T_('Hostname'),'type'=>'textbox'); $fields['host'] = array('description' => T_('Hostname'),'type'=>'textbox');
$fields['port'] = array('description' => T_('Port'),'type'=>'textbox'); $fields['port'] = array('description' => T_('Port'),'type'=>'textbox');
$fields['password'] = array('description' => T_('Password'),'type'=>'textbox'); $fields['password'] = array('description' => T_('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('vlc_active');
$instance = $instance ? $instance : Config::get('vlc_active'); $sql = "SELECT * FROM `localplay_vlc` WHERE `id` = ?";
$db_results = Dba::query($sql, array($instance));
$sql = "SELECT * FROM `localplay_vlc` WHERE `id` = ?";
$db_results = Dba::query($sql, array($instance));
$row = Dba::fetch_assoc($db_results); $row = Dba::fetch_assoc($db_results);
return $row; return $row;
} // get_instance } // get_instance
@ -219,33 +219,33 @@ class AmpacheVlc 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('vlc_active',$user_id,intval($uid)); Preference::update('vlc_active',$user_id,intval($uid));
Config::set('vlc_active', intval($uid), true); Config::set('vlc_active', intval($uid), true);
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
public function add_url(Stream_URL $url) { public function add_url(Stream_URL $url)
{
if (is_null($this->_vlc->add($url->title, $url->url))) { if (is_null($this->_vlc->add($url->title, $url->url))) {
debug_event('vlc', 'add_url failed to add: ' . json_encode($url), 1); debug_event('vlc', 'add_url failed to add: ' . json_encode($url), 1);
return false; return false;
@ -259,27 +259,27 @@ class AmpacheVlc 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 vlc webinterface * and delete them from vlc webinterface
*/ */
public function delete_track($object_id) { public function delete_track($object_id)
{
if (is_null($this->_vlc->delete_pos($object_id))) {
debug_event('vlc_del','ERROR Unable to delete ' . $object_id . ' from Vlc','1');
return false;
}
if (is_null($this->_vlc->delete_pos($object_id))) { return true;
debug_event('vlc_del','ERROR Unable to delete ' . $object_id . ' from Vlc','1');
return false;
}
return true;
} // delete_track } // delete_track
/** /**
* clear_playlist * clear_playlist
* This deletes the entire vlc playlist... nuff said * This deletes the entire vlc playlist... nuff said
*/ */
public function clear_playlist() { public function clear_playlist()
{
if (is_null($this->_vlc->clear())) { return false; } if (is_null($this->_vlc->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;
@ -290,15 +290,16 @@ class AmpacheVlc extends localplay_controller {
* This just tells vlc to start playing, it does not * This just tells vlc 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->_vlc->state() == 'play') { if ($this->_vlc->state() == 'play') {
return true; return true;
} }
if (is_null($this->_vlc->play())) { return false; } if (is_null($this->_vlc->play())) { return false; }
return true; return true;
} // play } // play
@ -308,9 +309,9 @@ class AmpacheVlc extends localplay_controller {
* This just tells vlc to stop playing, it does not take * This just tells vlc to stop playing, it does not take
* any arguments * any arguments
*/ */
public function stop() { public function stop()
{
if (is_null($this->_vlc->stop())) { return false; } if (is_null($this->_vlc->stop())) { return false; }
return true; return true;
} // stop } // stop
@ -319,19 +320,19 @@ class AmpacheVlc extends localplay_controller {
* skip * skip
* This tells vlc to skip to the specified song * This tells vlc to skip to the specified song
*/ */
public function skip($song) { public function skip($song)
{
if (is_null($this->_vlc->skip($song))) { return false; } if (is_null($this->_vlc->skip($song))) { return false; }
return true; return true;
} // skip } // skip
/** /**
* This tells vlc to increase the volume by in vlcplayerclass set amount * This tells vlc to increase the volume by in vlcplayerclass set amount
*/ */
public function volume_up() { public function volume_up()
{
if (is_null($this->_vlc->volume_up())) { return false; } if (is_null($this->_vlc->volume_up())) { return false; }
return true; return true;
} // volume_up } // volume_up
@ -339,21 +340,21 @@ class AmpacheVlc extends localplay_controller {
/** /**
* This tells vlc to decrease the volume by vlcplayerclass set amount * This tells vlc to decrease the volume by vlcplayerclass set amount
*/ */
public function volume_down() { public function volume_down()
{
if (is_null($this->_vlc->volume_down())) { return false; } if (is_null($this->_vlc->volume_down())) { return false; }
return true; return true;
} // volume_down } // volume_down
/** /**
* next * next
* This just tells vlc to skip to the next song, if you play a song by direct * This just tells vlc to skip to the next song, if you play a song by direct
* clicking and hit next vlc will start with the first song , needs work. * clicking and hit next vlc will start with the first song , needs work.
*/ */
public function next() { public function next()
{
if (is_null($this->_vlc->next())) { return false; } if (is_null($this->_vlc->next())) { return false; }
return true; return true;
@ -363,32 +364,32 @@ class AmpacheVlc extends localplay_controller {
* prev * prev
* This just tells vlc to skip to the prev song * This just tells vlc to skip to the prev song
*/ */
public function prev() { public function prev()
{
if (is_null($this->_vlc->prev())) { return false; } if (is_null($this->_vlc->prev())) { return false; }
return true; return true;
} // prev } // prev
/** /**
* pause * pause
* This tells vlc to pause the current song * This tells vlc to pause the current song
*/ */
public function pause() { public function pause()
{
if (is_null($this->_vlc->pause())) { return false; } if (is_null($this->_vlc->pause())) { return false; }
return true; return true;
} // pause } // pause
/** /**
* volume * volume
* This tells vlc to set the volume to the specified amount this * This tells vlc to set the volume to the specified amount this
* is 0-400 procent * is 0-400 procent
*/ */
public function volume($volume) { public function volume($volume)
{
if (is_null($this->_vlc->set_volume($volume))) { return false; } if (is_null($this->_vlc->set_volume($volume))) { return false; }
return true; return true;
@ -398,8 +399,8 @@ class AmpacheVlc extends localplay_controller {
* repeat * repeat
* This tells vlc to set the repeating the playlist (i.e. loop) to either on or off * This tells vlc 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->_vlc->repeat($state))) { return false; } if (is_null($this->_vlc->repeat($state))) { return false; }
return true; return true;
@ -409,8 +410,8 @@ class AmpacheVlc extends localplay_controller {
* random * random
* This tells vlc to turn on or off the playing of songs from the playlist in random order * This tells vlc to turn on or off the playing of songs from the playlist in random order
*/ */
public function random($onoff) { public function random($onoff)
{
if (is_null($this->_vlc->random($onoff))) { return false; } if (is_null($this->_vlc->random($onoff))) { return false; }
return true; return true;
@ -421,55 +422,51 @@ class AmpacheVlc extends localplay_controller {
* This functions returns an array containing information about * This functions returns an array containing information about
* The songs that vlc currently has in it's playlist. This must be * The songs that vlc currently has in it's playlist. This must be
* done in a standardized fashion * done in a standardized fashion
* Warning ! if you got files in vlc medialibary those files will be sent to the php xml parser * Warning ! if you got files in vlc medialibary those files will be sent to the php xml parser
* to, not to your browser but still this can take a lot of work for your server. * to, not to your browser but still this can take a lot of work for your server.
* The xml files of vlc need work, not much documentation on them.... * The xml files of vlc need work, not much documentation on them....
*/ */
public function get() { public function get()
{
/* Get the Current Playlist */ /* Get the Current Playlist */
$list = $this->_vlc->get_tracks(); $list = $this->_vlc->get_tracks();
if (!$list) { return array(); } if (!$list) { return array(); }
$counterforarray = 0; $counterforarray = 0;
// here we look if there are song in the playlist when media libary is used // here we look if there are song in the playlist when media libary is used
if ($list['node']['node'][0]['leaf'][$counterforarray]['attr']['uri']) { if ($list['node']['node'][0]['leaf'][$counterforarray]['attr']['uri']) {
while ($list['node']['node'][0]['leaf'][$counterforarray]){ while ($list['node']['node'][0]['leaf'][$counterforarray]) {
$songs[] = htmlspecialchars_decode($list['node']['node'][0]['leaf'][$counterforarray]['attr']['uri'], ENT_NOQUOTES); $songs[] = htmlspecialchars_decode($list['node']['node'][0]['leaf'][$counterforarray]['attr']['uri'], ENT_NOQUOTES);
$songid[] = $list['node']['node'][0]['leaf'][$counterforarray]['attr']['id']; $songid[] = $list['node']['node'][0]['leaf'][$counterforarray]['attr']['id'];
$counterforarray++; $counterforarray++;
} }
// if there is only one song look here,and media libary is used // if there is only one song look here,and media libary is used
} } elseif ($list['node']['node'][0]['leaf']['attr']['uri']) {
elseif($list['node']['node'][0]['leaf']['attr']['uri']) {
$songs[] = htmlspecialchars_decode($list['node']['node'][0]['leaf']['attr']['uri'], ENT_NOQUOTES); $songs[] = htmlspecialchars_decode($list['node']['node'][0]['leaf']['attr']['uri'], ENT_NOQUOTES);
$songid[] = $list['node']['node'][0]['leaf']['attr']['id']; $songid[] = $list['node']['node'][0]['leaf']['attr']['id'];
} }
// look for songs when media libary isn't used // look for songs when media libary isn't used
elseif ($list['node']['node']['leaf'][$counterforarray]['attr']['uri']) { elseif ($list['node']['node']['leaf'][$counterforarray]['attr']['uri']) {
while ($list['node']['node']['leaf'][$counterforarray]){ while ($list['node']['node']['leaf'][$counterforarray]) {
$songs[] = htmlspecialchars_decode($list['node']['node']['leaf'][$counterforarray]['attr']['uri'], ENT_NOQUOTES); $songs[] = htmlspecialchars_decode($list['node']['node']['leaf'][$counterforarray]['attr']['uri'], ENT_NOQUOTES);
$songid[] = $list['node']['node']['leaf'][$counterforarray]['attr']['id']; $songid[] = $list['node']['node']['leaf'][$counterforarray]['attr']['id'];
$counterforarray++; $counterforarray++;
} }
} } elseif ($list['node']['node']['leaf']['attr']['uri']) {
elseif ($list['node']['node']['leaf']['attr']['uri']) {
$songs[] = htmlspecialchars_decode($list['node']['node']['leaf']['attr']['uri'], ENT_NOQUOTES); $songs[] = htmlspecialchars_decode($list['node']['node']['leaf']['attr']['uri'], ENT_NOQUOTES);
$songid[] = $list['node']['node']['leaf']['attr']['id']; $songid[] = $list['node']['node']['leaf']['attr']['id'];
} } else { return array(); }
else { return array(); }
$counterforarray = 0;
foreach ($songs as $key=>$entry) {
$data = array();
/* Required Elements */
$data['id'] = $songid[$counterforarray]; // id number of the files in the vlc playlist, needed for other operations
$data['raw'] = $entry;
$url_data = $this->parse_url($entry); $counterforarray = 0;
foreach ($songs as $key=>$entry) {
$data = array();
/* Required Elements */
$data['id'] = $songid[$counterforarray]; // id number of the files in the vlc playlist, needed for other operations
$data['raw'] = $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']);
@ -482,10 +479,10 @@ class AmpacheVlc extends localplay_controller {
$data['name'] = T_('Democratic') . ' - ' . $democratic->name; $data['name'] = T_('Democratic') . ' - ' . $democratic->name;
$data['link'] = ''; $data['link'] = '';
break; break;
case 'random': case 'random':
$data['name'] = T_('Random') . ' - ' . scrub_out(ucfirst($url_data['type'])); $data['name'] = T_('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); $filename = Dba::escape($entry);
@ -495,10 +492,10 @@ class AmpacheVlc extends localplay_controller {
if ($row = Dba::fetch_assoc($db_results)) { if ($row = Dba::fetch_assoc($db_results)) {
//if stream is known just send name //if stream is known just send name
$data['name'] = htmlspecialchars(substr($row['name'], 0, 50)); $data['name'] = htmlspecialchars(substr($row['name'], 0, 50));
} }
//if it's a http stream not in ampacha's database just show the url' //if it's a http stream not in ampacha's database just show the url'
elseif ( strncmp($entry, 'http', 4)== 0) { elseif ( strncmp($entry, 'http', 4)== 0) {
$data['name'] = htmlspecialchars("(VLC stream) " . substr($entry, 0, 50)); $data['name'] = htmlspecialchars("(VLC stream) " . substr($entry, 0, 50));
} }
//if it's a file get the last output after and show that, hard to take every output possible in account //if it's a file get the last output after and show that, hard to take every output possible in account
@ -515,7 +512,7 @@ class AmpacheVlc extends localplay_controller {
$results[] = $data; $results[] = $data;
} // foreach playlist items } // foreach playlist items
return $results; return $results;
} // get } // get
@ -526,29 +523,29 @@ class AmpacheVlc extends localplay_controller {
* That this localplay method supports. required function * That this localplay method supports. required function
* This works as in requesting the status.xml file from vlc. * This works as in requesting the status.xml file from vlc.
*/ */
public function status() { public function status()
{
$arrayholder = $this->_vlc->fullstate(); //get status.xml via parser xmltoarray $arrayholder = $this->_vlc->fullstate(); //get status.xml via parser xmltoarray
/* Construct the Array */ /* Construct the Array */
$currentstat = $arrayholder['root']['state']['value']; $currentstat = $arrayholder['root']['state']['value'];
if ($currentstat == 'playing') { $state = 'play'; } //change to something ampache understands if ($currentstat == 'playing') { $state = 'play'; } //change to something ampache understands
if ($currentstat == 'stop') { $state = 'stop'; } if ($currentstat == 'stop') { $state = 'stop'; }
if ($currentstat == 'paused') { $state = 'pause'; } if ($currentstat == 'paused') { $state = 'pause'; }
$array['state'] = $state; $array['state'] = $state;
$array['volume'] = intval((intval($arrayholder['root']['volume']['value'])/2.6)); $array['volume'] = intval((intval($arrayholder['root']['volume']['value'])/2.6));
$array['repeat'] = $arrayholder['root']['repeat']['value']; $array['repeat'] = $arrayholder['root']['repeat']['value'];
$array['random'] = $arrayholder['root']['random']['value']; $array['random'] = $arrayholder['root']['random']['value'];
$array['track'] = htmlspecialchars_decode($arrayholder['root']['information']['meta-information']['title']['value'], ENT_NOQUOTES); $array['track'] = htmlspecialchars_decode($arrayholder['root']['information']['meta-information']['title']['value'], ENT_NOQUOTES);
$url_data = $this->parse_url($array['track']); $url_data = $this->parse_url($array['track']);
$song = new Song($url_data['oid']); $song = new Song($url_data['oid']);
if ($song->title || $song->get_artist_name() || $song->get_album_name()) { if ($song->title || $song->get_artist_name() || $song->get_album_name()) {
$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();
} }
// if not a known format // if not a known format
else { else {
$array['track_title'] = htmlspecialchars(substr($arrayholder['root']['information']['meta-information']['title']['value'], 0, 25)); $array['track_title'] = htmlspecialchars(substr($arrayholder['root']['information']['meta-information']['title']['value'], 0, 25));
@ -564,19 +561,17 @@ class AmpacheVlc 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->_vlc = new VlcPlayer($options['host'],$options['password'],$options['port']); $this->_vlc = new VlcPlayer($options['host'],$options['password'],$options['port']);
// Test our connection by retriving the version, no version in status file, just need to see if returned // Test our connection by retriving the version, no version in status file, just need to see if returned
//Not yet working all values returned are true for beta testing purpose //Not yet working all values returned are true for beta testing purpose
if (!is_null($this->_vlc->version())) { return true; } if (!is_null($this->_vlc->version())) { return true; }
return false; return false;
} // connect } // connect
} //end of AmpacheVlc
?> } //end of AmpacheVlc

Some files were not shown because too many files have changed in this diff Show more