diff --git a/manifest.json b/manifest.json
index 771ff99..c92d242 100644
--- a/manifest.json
+++ b/manifest.json
@@ -12,6 +12,9 @@
"email": "beudbeud@beudibox.fr"
},
"multi_instance": "true",
+ "requirements": {
+ "yunohost": ">> 2.3.12.1"
+ },
"services" : [
"nginx",
"php5-fpm",
diff --git a/scripts/install b/scripts/install
index 264b542..11b6ae7 100644
--- a/scripts/install
+++ b/scripts/install
@@ -1,14 +1,18 @@
#!/bin/bash
# Retrieve arguments
+app=$YNH_APP_INSTANCE_NAME
domain=$1
path=$2
admin_ampache=$3
-debianversionname=$(lsb_release -a | grep Codename | awk -F' ' '{print $2}')
+# Source YunoHost helpers
+. /usr/share/yunohost/helpers
+
+#debianversionname=$(lsb_release -a | grep Codename | awk -F' ' '{print $2}')
# Check domain/path availability
-sudo yunohost app checkurl $domain$path -a ampache
+sudo yunohost app checkurl $domain$path -a $app
if [[ ! $? -eq 0 ]]; then
exit 1
fi
@@ -26,14 +30,16 @@ sudo yunohost app setting ampache admin -v $admin_ampache
db_pwd=$(dd if=/dev/urandom bs=1 count=200 2> /dev/null | tr -c -d '[A-Za-z0-9]' | sed -n 's/\(.\{24\}\).*/\1/p')
# Use 'ampache' as database name and user
-db_user=ampache
+db_user=$app
# Initialize database and store mysql password for upgrade
-sudo yunohost app initdb $db_user -p $db_pwd -s $(readlink -e ../sources/sql/ampache.sql)
-sudo yunohost app setting ampache mysqlpwd -v $db_pwd
+#sudo yunohost app initdb $db_user -p $db_pwd -s $(readlink -e ../sources/sql/ampache.sql)
+sudo yunohost app setting $app mysqlpwd -v $db_pwd
+ynh_mysql_create_db "$app" "$db_user" "$db_pwd"
+ynh_mysql_connect_as "$db_user" "$db_pwd" "$app" < "../sources/sql/ampache.sql"
# Copy files to the right place
-final_path=/var/www/ampache
+final_path=/var/www/$app
sudo mkdir -p $final_path/log
sudo cp -a ../sources/* $final_path
sudo cp ../conf/ampache.cfg.php $final_path/config/ampache.cfg.php
@@ -55,29 +61,32 @@ sudo chown -R www-data: $final_path
# Modify Nginx configuration file and copy it to Nginx conf directory
sed -i "s@PATHTOCHANGE@${path%/}@g" ../conf/nginx.conf*
sed -i "s@ALIASTOCHANGE@$final_path/@g" ../conf/nginx.conf*
-sudo cp ../conf/nginx.conf /etc/nginx/conf.d/$domain.d/ampache.conf
+sudo cp ../conf/nginx.conf /etc/nginx/conf.d/$domain.d/$app.conf
# Reload Nginx and regenerate SSOwat conf
sudo service nginx reload
-sudo yunohost app setting ampache skipped_uris -v "/"
+sudo yunohost app setting $app skipped_uris -v "/"
sudo yunohost app ssowatconf
# Install dependency
-sudo apt-get install ffmpeg -y
+sudo apt-get install libav-tools -y
# Ampache installation
+cd /var/www/$app
+sudo php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
+sudo php composer-setup.php
+sudo php composer.phar install --prefer-source --no-interaction
+
echo "127.0.0.1 $domain #yunoampache" | sudo tee -a /etc/hosts
sleep 1
curl -kL -X POST http://$domain${path%/}/update.php?action=update > /dev/null 2>&1
sleep 5
-[ "$debianversionname" == "wheezy" ] && \
-sudo sed -i 's/;transcode_cmd = "ffmpeg"/transcode_cmd = "ffmpeg"/g' /var/www/ampache/config/ampache.cfg.php && \
-sudo sed -i 's/^transcode_cmd = "avconv"/;transcode_cmd = "avconv"/g' /var/www/ampache/config/ampache.cfg.php
-sudo yunohost app setting ampache skipped_uris -d
-sudo yunohost app setting ampache skipped_uris -v "/rest"
+
+sudo yunohost app setting $app skipped_uris -d
+sudo yunohost app setting $app skipped_uris -v "/rest"
sudo yunohost app ssowatconf
sudo sed '/yunoampache/d' /etc/hosts > /tmp/hosts.tmp
sudo cp /tmp/hosts.tmp /etc/hosts ; sudo rm -f /tmp/hosts.tmp
-mysql -u $db_user -p$db_pwd $db_user < /tmp/admin.sql
+ynh_mysql_connect_as "$db_user" "$db_pwd" "$app" < /tmp/admin.sql
sudo rm /tmp/admin.sql
diff --git a/scripts/remove b/scripts/remove
index dd02d9b..e763135 100644
--- a/scripts/remove
+++ b/scripts/remove
@@ -1,16 +1,17 @@
#!/bin/bash
-db_user=ampache
-db_name=ampache
+app=$YNH_APP_INSTANCE_NAME
+db_user=$app
+db_name=$app
root_pwd=$(sudo cat /etc/yunohost/mysql)
-domain=$(sudo yunohost app setting ampache domain)
+domain=$(sudo yunohost app setting $app domain)
# Drop MySQL database
mysql -u root -p$root_pwd -e "DROP DATABASE $db_name ; DROP USER $db_user@localhost ;"
# Remove sources
-sudo rm -rf /var/www/ampache
+sudo rm -rf /var/www/$app
# Remove Nginx configuration and reload Nginx conf
-sudo rm -f /etc/nginx/conf.d/$domain.d/ampache.conf
+sudo rm -f /etc/nginx/conf.d/$domain.d/$app.conf
sudo service nginx reload
diff --git a/scripts/upgrade b/scripts/upgrade
index e02caf0..a8f2b3e 100644
--- a/scripts/upgrade
+++ b/scripts/upgrade
@@ -1,20 +1,18 @@
#!/bin/bash
-
-debianversionname=$(lsb_release -a | grep Codename | awk -F' ' '{print $2}')
-
# Retrieve arguments
-domain=$(sudo yunohost app setting ampache domain)
-path=$(sudo yunohost app setting ampache path)
-db_user=ampache
-db_pwd=$(sudo yunohost app setting ampache mysqlpwd)
-admin_ampache=$(sudo yunohost app setting ampache admin)
+app=$YNH_APP_INSTANCE_NAME
+domain=$(sudo yunohost app setting $app domain)
+path=$(sudo yunohost app setting $app path)
+db_user=$app
+db_pwd=$(sudo yunohost app setting $app mysqlpwd)
+admin_ampache=$(sudo yunohost app setting $app admin)
# first make a copy of the db
-# mysqldump -u $db_user -p$db_pwd --add-drop-table --allow-keywords ampache > $final_path/ampache-db-backup.sql
+# mysqldump -u $db_user -p$db_pwd --add-drop-table --allow-keywords $app > $final_path/ampache-db-backup.sql
# Copy files to the right place
-final_path=/var/www/ampache
+final_path=/var/www/$app
sudo cp -a ../sources/* $final_path
sudo cp ../conf/ampache.cfg.php $final_path/config/ampache.cfg.php
@@ -32,12 +30,12 @@ sudo chown -R www-data: $final_path
# Modify Nginx configuration file and copy it to Nginx conf directory
sed -i "s@PATHTOCHANGE@${path%/}@g" ../conf/nginx.conf*
sed -i "s@ALIASTOCHANGE@$final_path/@g" ../conf/nginx.conf*
-sudo cp ../conf/nginx.conf /etc/nginx/conf.d/$domain.d/ampache.conf
+sudo cp ../conf/nginx.conf /etc/nginx/conf.d/$domain.d/$app.conf
# Reload Nginx and regenerate SSOwat conf
sudo service nginx reload
-sudo yunohost app setting ampache skipped_uris -v "/"
+sudo yunohost app setting $app skipped_uris -v "/"
sudo yunohost app ssowatconf
# Ampache installation
@@ -45,11 +43,9 @@ echo "127.0.0.1 $domain #yunoampache" | sudo tee -a /etc/hosts
sleep 1
curl -kL -X POST http://$domain${path%/}/update.php?action=update > /dev/null 2>&1
sleep 5
-[ "$debianversionname" == "wheezy" ] && \
-sudo sed -i 's/;transcode_cmd = "ffmpeg"/transcode_cmd = "ffmpeg"/g' /var/www/ampache/config/ampache.cfg.php && \
-sudo sed -i 's/^transcode_cmd = "avconv"/;transcode_cmd = "avconv"/g' /var/www/ampache/config/ampache.cfg.php
-sudo yunohost app setting ampache skipped_uris -d
-sudo yunohost app setting ampache skipped_uris -v "/rest"
+
+sudo yunohost app setting $app skipped_uris -d
+sudo yunohost app setting $app skipped_uris -v "/rest"
sudo yunohost app ssowatconf
sudo sed '/yunoampache/d' /etc/hosts > /tmp/hosts.tmp
sudo cp /tmp/hosts.tmp /etc/hosts ; sudo rm -f /tmp/hosts.tmp
diff --git a/sources/.gitignore b/sources/.gitignore
index 39e94cc..0fcfc8b 100644
--- a/sources/.gitignore
+++ b/sources/.gitignore
@@ -1,12 +1,24 @@
-config/ampache.cfg.php
-config/ampache-doped.cfg.php
-rest/.htaccess
-play/.htaccess
+/config/ampache.cfg.php
+/config/ampache-doped.cfg.php
+/rest/.htaccess
+/play/.htaccess
+/channel/.htaccess
*.phpproj
*.sln
*.v11.suo
*.suo
-logs
+/logs/
+/log/
/nbproject/private/
.pc
-/tmp
\ No newline at end of file
+/tmp/
+*~
+*#
+*.log
+/lib/vendor/
+/lib/components/
+web.config
+/config/motd.php
+/config/registration_agreement.php
+/.maintenance
+/modules/plugins/ampache-*
diff --git a/sources/.php_cs b/sources/.php_cs
index 8d80bfc..05748b2 100644
--- a/sources/.php_cs
+++ b/sources/.php_cs
@@ -3,12 +3,14 @@
use Symfony\CS\FixerInterface;
$finder = Symfony\CS\Finder\DefaultFinder::create()
+ ->exclude('lib/components')
+ ->exclude('lib/vendor')
->exclude('modules')
->exclude('nbproject')
->in(__DIR__)
->in(__DIR__ . '/modules/localplay')
->in(__DIR__ . '/modules/catalog')
- ->in(__DIR__ . '/modules/ampacheapi')
+ ->in(__DIR__ . '/modules/plugins')
;
return Symfony\CS\Config\Config::create()
diff --git a/sources/.scrutinizer.yml b/sources/.scrutinizer.yml
index 5de5f40..92e013c 100644
--- a/sources/.scrutinizer.yml
+++ b/sources/.scrutinizer.yml
@@ -1,5 +1,7 @@
filter:
excluded_paths:
+ - 'lib/components/*'
+ - 'lib/vendor/*'
- 'modules/*'
paths: { }
@@ -8,6 +10,8 @@ tools:
enabled: true
filter:
excluded_paths:
+ - 'lib/components/*'
+ - 'lib/vendor/*'
- 'modules/*'
- 'themes/*'
paths: { }
@@ -21,6 +25,8 @@ tools:
excluded_dirs: { }
filter:
excluded_paths:
+ - 'lib/components/*'
+ - 'lib/vendor/*'
- 'modules/*'
paths: { }
php_analyzer:
@@ -28,9 +34,13 @@ tools:
extensions:
- php
dependency_paths:
+ - 'lib/components/*'
+ - 'lib/vendor/*'
- 'modules/*'
filter:
excluded_paths:
+ - 'lib/components/*'
+ - 'lib/vendor/*'
- 'modules/*'
- 'themes/*'
paths: { }
@@ -44,16 +54,22 @@ tools:
- '\bimplement(?:s|ed)?\b'
filter:
excluded_paths:
+ - 'lib/components/*'
+ - 'lib/vendor/*'
- 'modules/*'
paths: { }
php_loc:
enabled: true
excluded_dirs:
+ - 'lib/components/*'
+ - 'lib/vendor/*'
- 'modules/*'
php_cpd:
enabled: true
excluded_dirs: { }
filter:
excluded_paths:
+ - 'lib/components/*'
+ - 'lib/vendor/*'
- 'modules/*'
paths: { }
\ No newline at end of file
diff --git a/sources/.travis.yml b/sources/.travis.yml
index 6f51e77..6ba9c67 100644
--- a/sources/.travis.yml
+++ b/sources/.travis.yml
@@ -4,9 +4,10 @@ php:
- 5.4
- 5.5
- 5.6
+ - 7.0
before_install:
- - wget http://cs.sensiolabs.org/get/php-cs-fixer.phar
+ - wget http://get.sensiolabs.org/php-cs-fixer.phar
before_script:
- chmod +x scripts/tests/syntax.sh
diff --git a/sources/CNAME b/sources/CNAME
deleted file mode 100644
index d5cfb4c..0000000
--- a/sources/CNAME
+++ /dev/null
@@ -1 +0,0 @@
-ampache.org
\ No newline at end of file
diff --git a/sources/README.md b/sources/README.md
old mode 100755
new mode 100644
index 73b9418..8a8deff
--- a/sources/README.md
+++ b/sources/README.md
@@ -1,6 +1,6 @@
-Ampache
+  Ampache
=======
-[www.ampache.org](http://www.ampache.org) |
+[www.ampache.org](http://ampache.org/) |
[ampache.github.io](http://ampache.github.io)
Basics
@@ -11,7 +11,7 @@ manager allowing you to access your music & videos from anywhere,
using almost any internet enabled device.
Ampache's usefulness is heavily dependent on being able to extract
-correct metadata from embedded tags in your files and/or the filename.
+correct metadata from embedded tags in your files and/or the file name.
Ampache is not a media organiser; it is meant to be a tool which
presents an already organised collection in a useful way. It assumes
that you know best how to manage your files and are capable of
@@ -20,15 +20,14 @@ choosing a suitable method for doing so.
Recommended Version
-------------------
-Currently, the recommended version is [git HEAD](https://github.com/ampache/ampache/archive/master.tar.gz).
+The recommended and most stable version is [git HEAD](https://github.com/ampache/ampache/archive/master.tar.gz).
[](https://travis-ci.org/ampache/ampache)
-Latest changes but unstable is [develop branch](https://github.com/ampache/ampache/archive/develop.tar.gz).
+You get the latest version with recent changes and fixes but maybe in an unstable state from our [develop branch](https://github.com/ampache/ampache/archive/develop.tar.gz).
[](https://travis-ci.org/ampache/ampache)
[](https://scrutinizer-ci.com/g/ampache/ampache/?branch=develop)
-[](https://www.codacy.com/app/afterster_2222/ampache)
+[](https://www.codacy.com/app/afterster_2222/ampache)
[](https://codeclimate.com/github/ampache/ampache)
-[](https://insight.sensiolabs.com/projects/ee067d0e-3432-4062-a969-01b4ee037f48)
Requirements
------------
@@ -48,7 +47,7 @@ receives the most testing:
* hash
* session
* json
- * simplexml (This is not strictly necessary, but may result in a better experience.)
+ * simplexml (This is not strictly necessary, but may result in a better experience.)
* curl (This is not strictly necessary, but may result in a better experience.)
* MySQL 5.x
@@ -63,34 +62,33 @@ Upgrading
If you are upgrading from an older version of Ampache we recommend
moving the old directory out of the way, extracting the new copy in
-its place and then copying the old config/ampache.cfg.php, /rest/.htaccess,
+its place and then copying the old /config/ampache.cfg.php, /rest/.htaccess,
and /play/.htaccess files if any. All database updates will be handled by Ampache.
License
-------
Ampache is free software; you can redistribute it and/or
-modify it under the terms of the GNU General Public License v2
+modify it under the terms of the GNU Affero General Public License v3 (AGPLv3)
as published by the Free Software Foundation.
Ampache includes some external modules that carry their own licensing.
* [getID3](http://getid3.sourceforge.net): GPL v2
* [Horde_Browser](http://www.horde.org): LGPL v2.1
-* [PHP-gettext](https://launchpad.net/php-gettext): GPL v2
+* [Gettext](https://github.com/oscarotero/Gettext): MIT
* [MusicBrainz](https://github.com/mikealmond/MusicBrainz): MIT
* PHP MPD interface: GPL v2
* [PHPMailer](https://github.com/PHPMailer/PHPMailer): LGPL v2.1
-* [jQuery](http://jquery.org): MIT
+* [jQuery](https://jquery.org/): MIT
* [Requests](http://requests.ryanmccue.info): ISC Licensed
-* [Whatever:hover](http://www.xs4all.nl/~peterned): LGPL v2.1
-* [xbmc-php-rpc](https://github.com/karlrixon/xbmc-php-rpc): GPL v3
+* [xbmc-php-rpc](https://github.com/krixon/xbmc-php-rpc): GPL v3
* [Dropbox SDK](https://github.com/dropbox/dropbox-sdk-php): MIT
* [jPlayer](http://jplayer.org): MIT
* [prettyPhoto](http://www.no-margin-for-errors.com/projects/prettyphoto-jquery-lightbox-clone): GPL v2
* [Tag-it!] (http://aehlke.github.io/tag-it): MIT
* [PHP Echo Nest API] (https://github.com/bshaffer/php-echonest-api): MIT
-* [Noty] (http://ned.im/noty): MIT
+* [Noty] (http://ned.im/noty/): MIT
* [jScroll] (https://github.com/pklauzinski/jscroll): MIT
* [jquery.qrcode] (http://jeromeetienne.github.io/jquery-qrcode): MIT
* [PHP OpenID] (https://github.com/openid/php-openid): Apache License
@@ -99,14 +97,14 @@ Ampache includes some external modules that carry their own licensing.
* [Guzzle] (https://github.com/guzzle/guzzle): MIT
* [Symfony Components] (https://github.com/symfony): MIT
* [Evenement] (https://github.com/igorw/evenement): MIT
-* [RhinoSlider] (http://rhinoslider.com): MIT
+* [RhinoSlider] (http://www.rhinoslider.com/): MIT
* [MediaTable] (https://github.com/edenspiekermann/MediaTable): MIT
* [Responsive Elements] (https://github.com/kumailht/responsive-elements): MIT
* [Bootstrap] (http://getbootstrap.com): MIT
* [jQuery Knob] (https://github.com/aterrien/jQuery-Knob): MIT
* [jQuery File Upload] (https://github.com/blueimp/jQuery-File-Upload): MIT
-* [jsTree] (http://www.jstree.com): MIT
-* [php-tmdb-api] (https://github.com/wtfzdotnet/php-tmdb-api) : MIT
+* [jsTree] (https://www.jstree.com/): MIT
+* [php-tmdb-api] (https://github.com/php-tmdb/api) : MIT
* [TvDb] (https://github.com/Moinax/TvDb) : MIT
* [jQuery DateTimePicker] (https://github.com/xdan/datetimepicker) : MIT
* [pChart] (http://www.pchart.net) : GPL v3
@@ -119,27 +117,13 @@ Translations
Ampache is currently translated (at least partially) into the
following languages. If you are interested in updating an existing
-translation or adding a new one please see /locale/base/TRANSLATIONS
+translation, simply visit us on [Transifex](https://www.transifex.com/ampache/ampache).
+If you prefer it old school or want to work offline, take a look at [/locale/base/TRANSLATIONS](https://github.com/ampache/ampache/blob/develop/locale/base/TRANSLATIONS.md)
for more instructions.
-* English (en_US)
-* Arabic (ar_SA)
-* Catalan (ca_ES)
-* Catalan (ca_ES)
-* Czech (cs_CZ)
-* Dutch (nl_NL)
-* French (fr_FR)
-* German (de_DE)
-* Greek (el_GR)
-* Italian (it_IT)
-* Japanese (ja_JP)
-* Norwegian (nb_NO)
-* Persian (fa_IR)
-* Polish (pl_PL)
-* Russian (ru_RU)
-* Spanish (es_ES)
-* Swedish (sv_SE)
-* UK English (en_GB)
+Translation progress so far:
+
+[](https://www.transifex.com/projects/p/ampache/)
Credits
-------
@@ -150,12 +134,18 @@ Thanks to all those who have helped make Ampache awesome: [Credits](docs/ACKNOWL
Contact Us
----------
-Hate it? Love it? Let us know. Also let us know if you think of any
-more features, encounter bugs, etc.
+Hate it? Love it? Let us know! Dozens of people send ideas for amazing new features, report bugs and further develop Ampache actively. Be a part of Ampache with it's more than 10 years long history and get in touch with an awesome and friendly community!
-* [Public Repository](http://github.com/ampache)
-* IRC: chat.freenode.net #ampache
-* [Forum](https://groups.google.com/forum/#!forum/ampache)
-* [Issue Tracker](https://github.com/ampache/ampache/issues)
-* [Documentation](https://github.com/ampache/ampache/wiki)
+* For Live discussions, visit us on our IRC Channel at chat.freenode.net #ampache or alternative via a [web based chat client](https://webchat.freenode.net)
+* For harder cases or general discussion about Ampache take a look at our [Google Groups Forum](https://groups.google.com/forum/#!forum/ampache)
+* Found a bug or Ampache isn't working as expected? Head over to our [Issue Tracker](https://github.com/ampache/ampache/issues)
+Further Information and basic Help
+----------------------------------
+
+* Everything related to the Ampache Project can be found on our [Public Repository](https://github.com/ampache)
+* Want to know, how to get Apache to work or learn more about the functions? See our [Documentation](https://github.com/ampache/ampache/wiki)
+
+We hope to see you soon and that you have fun with this Project!
+
+[Team Ampache](docs/ACKNOWLEDGEMENTS)
diff --git a/sources/admin/access.php b/sources/admin/access.php
index 5c48f78..ee66149 100644
--- a/sources/admin/access.php
+++ b/sources/admin/access.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -40,7 +40,9 @@ switch ($_REQUEST['action']) {
show_confirmation(T_('Deleted'), T_('Your Access List Entry has been removed'),$url);
break;
case 'show_delete_record':
- if (AmpConfig::get('demo_mode')) { break; }
+ if (AmpConfig::get('demo_mode')) {
+ break;
+ }
$access = new Access($_GET['access_id']);
show_confirmation(T_('Deletion Request'), T_('Are you sure you want to permanently delete') . ' ' . $access->name,
'admin/access.php?action=delete_record&access_id=' . $access->id,1,'delete_access');
@@ -67,12 +69,12 @@ switch ($_REQUEST['action']) {
Access::create($_POST);
}
- if (!Error::occurred()) {
+ if (!AmpError::occurred()) {
$url = AmpConfig::get('web_path') . '/admin/access.php';
show_confirmation(T_('Added'), T_('Your new Access Control List(s) have been created'),$url);
} else {
$action = 'show_add_' . $_POST['type'];
- require_once AmpConfig::get('prefix') . '/templates/show_add_access.inc.php';
+ require_once AmpConfig::get('prefix') . UI::find_template('show_add_access.inc.php');
}
break;
case 'update_record':
@@ -82,11 +84,11 @@ switch ($_REQUEST['action']) {
}
$access = new Access($_REQUEST['access_id']);
$access->update($_POST);
- if (!Error::occurred()) {
- show_confirmation(T_('Updated'), T_('Access List Entry updated'), AmpConfig::get('web_path').'/admin/access.php');
+ if (!AmpError::occurred()) {
+ show_confirmation(T_('Updated'), T_('Access List Entry updated'), AmpConfig::get('web_path') . '/admin/access.php');
} else {
$access->format();
- require_once AmpConfig::get('prefix') . '/templates/show_edit_access.inc.php';
+ require_once AmpConfig::get('prefix') . UI::find_template('show_edit_access.inc.php');
}
break;
case 'show_add_current':
@@ -94,17 +96,17 @@ switch ($_REQUEST['action']) {
case 'show_add_local':
case 'show_add_advanced':
$action = $_REQUEST['action'];
- require_once AmpConfig::get('prefix') . '/templates/show_add_access.inc.php';
+ require_once AmpConfig::get('prefix') . UI::find_template('show_add_access.inc.php');
break;
case 'show_edit_record':
$access = new Access($_REQUEST['access_id']);
$access->format();
- require_once AmpConfig::get('prefix') . '/templates/show_edit_access.inc.php';
+ require_once AmpConfig::get('prefix') . UI::find_template('show_edit_access.inc.php');
break;
default:
$list = array();
$list = Access::get_access_lists();
- require_once AmpConfig::get('prefix') .'/templates/show_access_list.inc.php';
+ require_once AmpConfig::get('prefix') . UI::find_template('show_access_list.inc.php');
break;
} // end switch on action
UI::show_footer();
diff --git a/sources/admin/catalog.php b/sources/admin/catalog.php
index 61372dd..6c40a32 100644
--- a/sources/admin/catalog.php
+++ b/sources/admin/catalog.php
@@ -2,26 +2,26 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
require_once '../lib/init.php';
-require_once AmpConfig::get('prefix') . '/modules/catalog/local.catalog.php';
+require_once AmpConfig::get('prefix') . '/modules/catalog/local/local.catalog.php';
if (!Access::check('interface','100')) {
UI::access_denied();
@@ -45,43 +45,47 @@ if (is_array($catalogs) && count($catalogs) == 1 && $_REQUEST['action'] !== 'del
}
}
}
-$sse_catalogs = urlencode(serialize($catalogs));
+
/* Big switch statement to handle various actions */
switch ($_REQUEST['action']) {
case 'add_to_all_catalogs':
- $sse_url = AmpConfig::get('web_path') . "/server/sse.server.php?worker=catalog&action=add_to_all_catalogs";
- sse_worker($sse_url);
+ catalog_worker('add_to_all_catalogs');
show_confirmation(T_('Catalog Update started...'), '', AmpConfig::get('web_path') . '/admin/catalog.php', 0, 'confirmation', false);
break;
case 'add_to_catalog':
- if (AmpConfig::get('demo_mode')) { break; }
+ if (AmpConfig::get('demo_mode')) {
+ break;
+ }
- $sse_url = AmpConfig::get('web_path') . "/server/sse.server.php?worker=catalog&action=add_to_catalog&catalogs=" . $sse_catalogs;
- sse_worker($sse_url);
+ catalog_worker('add_to_catalog', $catalogs);
show_confirmation(T_('Catalog Update started...'), '', AmpConfig::get('web_path') . '/admin/catalog.php', 0, 'confirmation', false);
break;
case 'update_all_catalogs':
- $sse_url = AmpConfig::get('web_path') . "/server/sse.server.php?worker=catalog&action=update_all_catalogs";
- sse_worker($sse_url);
+ catalog_worker('update_all_catalogs');
show_confirmation(T_('Catalog Update started...'), '', AmpConfig::get('web_path') . '/admin/catalog.php', 0, 'confirmation', false);
break;
case 'update_catalog':
- if (AmpConfig::get('demo_mode')) { break; }
+ if (AmpConfig::get('demo_mode')) {
+ break;
+ }
- $sse_url = AmpConfig::get('web_path') . "/server/sse.server.php?worker=catalog&action=update_catalog&catalogs=" . $sse_catalogs;
- sse_worker($sse_url);
+ catalog_worker('update_catalog', $catalogs);
show_confirmation(T_('Catalog Update started...'), '', AmpConfig::get('web_path') . '/admin/catalog.php', 0, 'confirmation', false);
break;
case 'full_service':
- if (AmpConfig::get('demo_mode')) { UI::access_denied(); break; }
+ if (AmpConfig::get('demo_mode')) {
+ UI::access_denied();
+ break;
+ }
- $sse_url = AmpConfig::get('web_path') . "/server/sse.server.php?worker=catalog&action=full_service&catalogs=" . $sse_catalogs;
- sse_worker($sse_url);
+ catalog_worker('full_service', $catalogs);
show_confirmation(T_('Catalog Update started...'), '', AmpConfig::get('web_path') . '/admin/catalog.php', 0, 'confirmation', false);
break;
case 'delete_catalog':
- if (AmpConfig::get('demo_mode')) { break; }
+ if (AmpConfig::get('demo_mode')) {
+ break;
+ }
if (!Core::form_verify('delete_catalog')) {
UI::access_denied();
@@ -92,7 +96,9 @@ switch ($_REQUEST['action']) {
/* Delete the sucker, we don't need to check perms as thats done above */
foreach ($catalogs as $catalog_id) {
$deleted = Catalog::delete($catalog_id);
- if (!$deleted) break;
+ if (!$deleted) {
+ break;
+ }
}
$next_url = AmpConfig::get('web_path') . '/admin/catalog.php';
if ($deleted) {
@@ -106,7 +112,9 @@ switch ($_REQUEST['action']) {
show_confirmation(T_('Catalog Delete'), T_('Confirm Deletion Request'),$next_url,1,'delete_catalog');
break;
case 'enable_disabled':
- if (AmpConfig::get('demo_mode')) { break; }
+ if (AmpConfig::get('demo_mode')) {
+ break;
+ }
$songs = $_REQUEST['song'];
@@ -118,51 +126,54 @@ switch ($_REQUEST['action']) {
} else {
$body = T_('No Disabled Songs selected');
}
- $url = AmpConfig::get('web_path') . '/admin/catalog.php';
+ $url = AmpConfig::get('web_path') . '/admin/catalog.php';
$title = count($songs) . ngettext(' Disabled Song Processed', ' Disabled Songs Processed', count($songs));
show_confirmation($title,$body,$url);
break;
case 'clean_all_catalogs':
- $sse_url = AmpConfig::get('web_path') . "/server/sse.server.php?worker=catalog&action=clean_all_catalogs";
- sse_worker($sse_url);
+ catalog_worker('clean_all_catalogs');
show_confirmation(T_('Catalog Clean started...'), '', AmpConfig::get('web_path') . '/admin/catalog.php', 0, 'confirmation', false);
break;
case 'clean_catalog':
- $sse_url = AmpConfig::get('web_path') . "/server/sse.server.php?worker=catalog&action=clean_catalog&catalogs=" . $sse_catalogs;
- sse_worker($sse_url);
+ catalog_worker('clean_catalog', $catalogs);
show_confirmation(T_('Catalog Clean started...'), '', AmpConfig::get('web_path') . '/admin/catalog.php', 0, 'confirmation', false);
break;
case 'update_catalog_settings':
/* No Demo Here! */
- if (AmpConfig::get('demo_mode')) { break; }
+ if (AmpConfig::get('demo_mode')) {
+ break;
+ }
/* Update the catalog */
Catalog::update_settings($_POST);
- $url = AmpConfig::get('web_path') . '/admin/catalog.php';
+ $url = AmpConfig::get('web_path') . '/admin/catalog.php';
$title = T_('Catalog Updated');
- $body = '';
+ $body = '';
show_confirmation($title,$body,$url);
break;
case 'update_from':
- if (AmpConfig::get('demo_mode')) { break; }
+ if (AmpConfig::get('demo_mode')) {
+ break;
+ }
- $sse_url = AmpConfig::get('web_path') . "/server/sse.server.php?worker=catalog&action=update_from&add_path=" . scrub_in($_POST['add_path']) . "&update_path=" . $_POST['update_path'];
- sse_worker($sse_url);
+ catalog_worker('update_from', null, $_POST);
show_confirmation(T_('Subdirectory update started...'), '', AmpConfig::get('web_path') . '/admin/catalog.php', 0, 'confirmation', false);
break;
case 'add_catalog':
/* Wah Demo! */
- if (AmpConfig::get('demo_mode')) { break; }
+ if (AmpConfig::get('demo_mode')) {
+ break;
+ }
ob_end_flush();
if (!strlen($_POST['type']) || $_POST['type'] == 'none') {
- Error::add('general', T_('Error: Please select a catalog type'));
+ AmpError::add('general', T_('Error: Please select a catalog type'));
}
if (!strlen($_POST['name'])) {
- Error::add('general', T_('Error: Name not specified'));
+ AmpError::add('general', T_('Error: Name not specified'));
}
if (!Core::form_verify('add_catalog','post')) {
@@ -171,53 +182,62 @@ switch ($_REQUEST['action']) {
}
// If an error hasn't occured
- if (!Error::occurred()) {
-
+ if (!AmpError::occurred()) {
$catalog_id = Catalog::create($_POST);
if (!$catalog_id) {
- require AmpConfig::get('prefix') . '/templates/show_add_catalog.inc.php';
+ require AmpConfig::get('prefix') . UI::find_template('show_add_catalog.inc.php');
break;
}
- $sse_url = AmpConfig::get('web_path') . "/server/sse.server.php?worker=catalog&action=add_catalog&catalog_id=" . $catalog_id . "&options=" . urlencode(serialize($_POST));
- sse_worker($sse_url);
-
+ $catalogs[] = $catalog_id;
+ catalog_worker('add_to_catalog', $catalogs, $_POST);
show_confirmation(T_('Catalog Creation started...'), '', AmpConfig::get('web_path') . '/admin/catalog.php', 0, 'confirmation', false);
} else {
- require AmpConfig::get('prefix') . '/templates/show_add_catalog.inc.php';
+ require AmpConfig::get('prefix') . UI::find_template('show_add_catalog.inc.php');
}
break;
case 'clear_stats':
- if (AmpConfig::get('demo_mode')) { UI::access_denied(); break; }
+ if (AmpConfig::get('demo_mode')) {
+ UI::access_denied();
+ break;
+ }
Stats::clear();
- $url = AmpConfig::get('web_path') . '/admin/catalog.php';
+ $url = AmpConfig::get('web_path') . '/admin/catalog.php';
$title = T_('Catalog statistics cleared');
- $body = '';
+ $body = '';
show_confirmation($title, $body, $url);
break;
case 'show_add_catalog':
- require AmpConfig::get('prefix') . '/templates/show_add_catalog.inc.php';
+ require AmpConfig::get('prefix') . UI::find_template('show_add_catalog.inc.php');
break;
case 'clear_now_playing':
- if (AmpConfig::get('demo_mode')) { UI::access_denied(); break; }
+ if (AmpConfig::get('demo_mode')) {
+ UI::access_denied();
+ break;
+ }
Stream::clear_now_playing();
show_confirmation(T_('Now Playing Cleared'), T_('All now playing data has been cleared'),AmpConfig::get('web_path') . '/admin/catalog.php');
break;
case 'show_disabled':
/* Stop the demo hippies */
- if (AmpConfig::get('demo_mode')) { break; }
+ if (AmpConfig::get('demo_mode')) {
+ break;
+ }
$songs = Song::get_disabled();
if (count($songs)) {
- require AmpConfig::get('prefix') . '/templates/show_disabled_songs.inc.php';
+ require AmpConfig::get('prefix') . UI::find_template('show_disabled_songs.inc.php');
} else {
echo "
";
+ // This to keep browser cache feature but force a refresh in case image just changed
+ if (Art::has_db($object_id, $object_type)) {
+ $art = new Art($object_id, $object_type);
+ if ($art->get_db()) {
+ $imgurl .= '&fooid=' . $art->id;
}
-
+ }
+ echo "";
+
+ if ($size['height'] > 150) {
+ echo "
";
+ }
+
+ if ($prettyPhoto) {
$libitem = new $object_type($object_id);
echo "
";
if ($GLOBALS['user']->has_access(50) || ($GLOBALS['user']->has_access(25) && $GLOBALS['user']->id == $libitem->get_user_owner())) {
@@ -1728,10 +1768,11 @@ class Art extends database_object
}
echo"
";
}
+
echo "\n";
echo "";
return true;
}
-
} // Art
+
diff --git a/sources/lib/class/artist.class.php b/sources/lib/class/artist.class.php
index 11587a8..f55fcc1 100644
--- a/sources/lib/class/artist.class.php
+++ b/sources/lib/class/artist.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -76,6 +76,10 @@ class Artist extends database_object implements library_item
* @var int $user
*/
public $user;
+ /**
+ * @var boolean $manual_update
+ */
+ public $manual_update;
/**
* @var array $tags
@@ -139,7 +143,9 @@ class Artist extends database_object implements library_item
public function __construct($id=null,$catalog_init=0)
{
/* If they failed to pass in an id, just run for it */
- if (!$id) { return false; }
+ if (!$id) {
+ return false;
+ }
$this->catalog_id = $catalog_init;
/* Get the information from the db */
@@ -150,7 +156,6 @@ class Artist extends database_object implements library_item
} // foreach info
return true;
-
} //constructor
/**
@@ -171,7 +176,6 @@ class Artist extends database_object implements library_item
$artist->_fake = true;
return $artist;
-
} // construct_from_array
/**
@@ -196,15 +200,17 @@ class Artist extends database_object implements library_item
*/
public static function build_cache($ids, $extra=false, $limit_threshold = '')
{
- if (!is_array($ids) OR !count($ids)) { return false; }
+ if (!is_array($ids) or !count($ids)) {
+ return false;
+ }
$idlist = '(' . implode(',', $ids) . ')';
- $sql = "SELECT * FROM `artist` WHERE `id` IN $idlist";
+ $sql = "SELECT * FROM `artist` WHERE `id` IN $idlist";
$db_results = Dba::read($sql);
- while ($row = Dba::fetch_assoc($db_results)) {
- parent::add_to_cache('artist',$row['id'],$row);
+ while ($row = Dba::fetch_assoc($db_results)) {
+ parent::add_to_cache('artist',$row['id'],$row);
}
// If we need to also pull the extra information, this is normally only used when we are doing the human display
@@ -220,11 +226,9 @@ class Artist extends database_object implements library_item
}
parent::add_to_cache('artist_extra',$row['artist'],$row);
}
-
} // end if extra
return true;
-
} // build_cache
/**
@@ -235,7 +239,7 @@ class Artist extends database_object implements library_item
*/
public static function get_from_name($name)
{
- $sql = "SELECT `id` FROM `artist` WHERE `name` = ?'";
+ $sql = "SELECT `id` FROM `artist` WHERE `name` = ?'";
$db_results = Dba::read($sql, array($name));
$row = Dba::fetch_assoc($db_results);
@@ -243,7 +247,6 @@ class Artist extends database_object implements library_item
$object = new Artist($row['id']);
return $object;
-
} // get_from_name
/**
@@ -258,7 +261,7 @@ class Artist extends database_object implements library_item
public function get_albums($catalog = null, $ignoreAlbumGroups = false, $group_release_type = false)
{
$catalog_where = "";
- $catalog_join = "LEFT JOIN `catalog` ON `catalog`.`id` = `song`.`catalog`";
+ $catalog_join = "LEFT JOIN `catalog` ON `catalog`.`id` = `song`.`catalog`";
if ($catalog) {
$catalog_where .= " AND `catalog`.`id` = '" . $catalog . "'";
}
@@ -269,7 +272,7 @@ class Artist extends database_object implements library_item
$results = array();
$sort_type = AmpConfig::get('album_sort');
- $sql_sort = '`album`.`name`,`album`.`disk`,`album`.`year`';
+ $sql_sort = '`album`.`name`,`album`.`disk`,`album`.`year`';
if ($sort_type == 'year_asc') {
$sql_sort = '`album`.`year` ASC';
} elseif ($sort_type == 'year_desc') {
@@ -280,48 +283,50 @@ class Artist extends database_object implements library_item
$sql_sort = '`album`.`name` DESC';
}
- $sql_group_type = '`album`.`id`';
- if (!$ignoreAlbumGroups && AmpConfig::get('album_group')) {
- $sql_group_type = '`album`.`mbid`';
+ if (!$ignoreAlbumGroups) {
+ $ignoreAlbumGroups = !AmpConfig::get('album_group');
}
- $sql_group = "COALESCE($sql_group_type, `album`.`id`)";
- $sql = "SELECT `album`.`id`, `album`.`release_type` FROM album LEFT JOIN `song` ON `song`.`album`=`album`.`id` $catalog_join " .
- "WHERE (`song`.`artist`='$this->id' OR `album`.`album_artist`='$this->id') $catalog_where GROUP BY $sql_group ORDER BY $sql_sort";
+ $sql = "SELECT `album`.`id`, `album`.`release_type`,`album`.`mbid` FROM album LEFT JOIN `song` ON `song`.`album`=`album`.`id` $catalog_join " .
+ "WHERE (`song`.`artist`='$this->id' OR `album`.`album_artist`='$this->id') $catalog_where GROUP BY `album`.`id`, `album`.`release_type`,`album`.`mbid` ORDER BY $sql_sort";
- debug_event("Artist", "$sql", "6");
$db_results = Dba::read($sql);
+ $mbids = array();
while ($r = Dba::fetch_assoc($db_results)) {
- if ($group_release_type) {
- // We assume undefined release type is album
- $rtype = $r['release_type'] ?: 'album';
- if (!isset($results[$rtype])) {
- $results[$rtype] = array();
- }
- $results[$rtype][] = $r['id'];
-
- $sort = AmpConfig::get('album_release_type_sort');
- if ($sort) {
- $results_sort = array();
- $asort = explode(',', $sort);
-
- foreach ($asort as $rtype) {
- if (array_key_exists($rtype, $results)) {
- $results_sort[$rtype] = $results[$rtype];
- unset($results[$rtype]);
- }
+ if ($ignoreAlbumGroups || empty($r['mbid']) || !in_array($r['mbid'], $mbids)) {
+ if ($group_release_type) {
+ // We assume undefined release type is album
+ $rtype = $r['release_type'] ?: 'album';
+ if (!isset($results[$rtype])) {
+ $results[$rtype] = array();
}
+ $results[$rtype][] = $r['id'];
- $results = array_merge($results_sort, $results);
+ $sort = AmpConfig::get('album_release_type_sort');
+ if ($sort) {
+ $results_sort = array();
+ $asort = explode(',', $sort);
+
+ foreach ($asort as $rtype) {
+ if (array_key_exists($rtype, $results)) {
+ $results_sort[$rtype] = $results[$rtype];
+ unset($results[$rtype]);
+ }
+ }
+
+ $results = array_merge($results_sort, $results);
+ }
+ } else {
+ $results[] = $r['id'];
+ }
+ if (!empty($r['mbid'])) {
+ $mbids[] = $r['mbid'];
}
- } else {
- $results[] = $r['id'];
}
}
return $results;
-
} // get_albums
/**
@@ -348,7 +353,6 @@ class Artist extends database_object implements library_item
}
return $results;
-
} // get_songs
/**
@@ -376,7 +380,6 @@ class Artist extends database_object implements library_item
}
return $results;
-
} // get_random_songs
/**
@@ -391,20 +394,30 @@ class Artist extends database_object implements library_item
if (parent::is_cached('artist_extra',$this->id) ) {
$row = parent::get_from_cache('artist_extra',$this->id);
} else {
- $uid = Dba::escape($this->id);
- $sql = "SELECT `song`.`artist`,COUNT(DISTINCT `song`.`id`) AS `song_count`, COUNT(DISTINCT `song`.`album`) AS `album_count`, SUM(`song`.`time`) AS `time`, `song`.`catalog` as `catalog_id` FROM `song` LEFT JOIN `catalog` ON `catalog`.`id` = `song`.`catalog` " .
- "WHERE `song`.`artist`='$uid' ";
+ $params = array($this->id);
+ // Calculation
+ $sql = "SELECT COUNT(DISTINCT `song`.`id`) AS `song_count`, COUNT(DISTINCT `song`.`album`) AS `album_count`, SUM(`song`.`time`) AS `time` FROM `song` LEFT JOIN `catalog` ON `catalog`.`id` = `song`.`catalog` ";
+ $sqlw = "WHERE `song`.`artist` = ? ";
if ($catalog) {
- $sql .= "AND (`song`.`catalog` = '$catalog') ";
+ $params[] = $catalog;
+ $sqlw .= "AND (`song`.`catalog` = ?) ";
}
if (AmpConfig::get('catalog_disable')) {
- $sql .= " AND `catalog`.`enabled` = '1'";
+ $sqlw .= " AND `catalog`.`enabled` = '1' ";
}
+ $sql .= $sqlw . "GROUP BY `song`.`artist`";
- $sql .= "GROUP BY `song`.`artist`";
-
- $db_results = Dba::read($sql);
- $row = Dba::fetch_assoc($db_results);
+ $db_results = Dba::read($sql, $params);
+ $row = Dba::fetch_assoc($db_results);
+
+
+ // Get associated information from first song only
+ $sql = "SELECT `song`.`artist`, `song`.`catalog` as `catalog_id` FROM `song` LEFT JOIN `catalog` ON `catalog`.`id` = `song`.`catalog` ";
+ $sql .= $sqlw . "LIMIT 1";
+
+ $db_results = Dba::read($sql, $params);
+ $row = array_merge($row, Dba::fetch_assoc($db_results));
+
if (AmpConfig::get('show_played_times')) {
$row['object_cnt'] = Stats::get_object_count('artist', $row['artist'], $limit_threshold);
}
@@ -412,13 +425,12 @@ class Artist extends database_object implements library_item
}
/* Set Object Vars */
- $this->songs = $row['song_count'];
- $this->albums = $row['album_count'];
- $this->time = $row['time'];
+ $this->songs = $row['song_count'];
+ $this->albums = $row['album_count'];
+ $this->time = $row['time'];
$this->catalog_id = $row['catalog_id'];
return $row;
-
} // _get_extra_info
/**
@@ -432,18 +444,20 @@ class Artist extends database_object implements library_item
public function format($details = true, $limit_threshold = '')
{
/* Combine prefix and name, trim then add ... if needed */
- $name = trim($this->prefix . " " . $this->name);
- $this->f_name = $name;
+ $name = trim($this->prefix . " " . $this->name);
+ $this->f_name = $name;
$this->f_full_name = trim(trim($this->prefix) . ' ' . trim($this->name));
// If this is a memory-only object, we're done here
- if (!$this->id) { return true; }
+ if (!$this->id) {
+ return true;
+ }
if ($this->catalog_id) {
- $this->link = AmpConfig::get('web_path') . '/artists.php?action=show&catalog=' . $this->catalog_id . '&artist=' . $this->id;
+ $this->link = AmpConfig::get('web_path') . '/artists.php?action=show&catalog=' . $this->catalog_id . '&artist=' . $this->id;
$this->f_link = "link . "\" title=\"" . $this->f_full_name . "\">" . $name . "";
} else {
- $this->link = AmpConfig::get('web_path') . '/artists.php?action=show&artist=' . $this->id;
+ $this->link = AmpConfig::get('web_path') . '/artists.php?action=show&artist=' . $this->id;
$this->f_link = "link . "\" title=\"" . $this->f_full_name . "\">" . $name . "";
}
@@ -454,16 +468,16 @@ class Artist extends database_object implements library_item
//Format the new time thingy that we just got
$min = sprintf("%02d",(floor($extra_info['time']/60)%60));
- $sec = sprintf("%02d",($extra_info['time']%60));
+ $sec = sprintf("%02d",($extra_info['time']%60));
$hours = floor($extra_info['time']/3600);
$this->f_time = ltrim($hours . ':' . $min . ':' . $sec,'0:');
- $this->tags = Tag::get_top_tags('artist', $this->id);
+ $this->tags = Tag::get_top_tags('artist', $this->id);
$this->f_tags = Tag::get_display($this->tags, true, 'artist');
if (AmpConfig::get('label')) {
- $this->labels = Label::get_labels($this->id);
+ $this->labels = Label::get_labels($this->id);
$this->f_labels = Label::get_display($this->labels, true);
}
@@ -471,7 +485,6 @@ class Artist extends database_object implements library_item
}
return true;
-
} // format
/**
@@ -480,7 +493,7 @@ class Artist extends database_object implements library_item
*/
public function get_keywords()
{
- $keywords = array();
+ $keywords = array();
$keywords['mb_artistid'] = array('important' => false,
'label' => T_('Artist MusicBrainzID'),
'value' => $this->mbid);
@@ -533,14 +546,14 @@ class Artist extends database_object implements library_item
*/
public function search_childrens($name)
{
- $search['type'] = "album";
- $search['rule_0_input'] = $name;
+ $search['type'] = "album";
+ $search['rule_0_input'] = $name;
$search['rule_0_operator'] = 4;
- $search['rule_0'] = "title";
- $search['rule_1_input'] = $this->name;
+ $search['rule_0'] = "title";
+ $search['rule_1_input'] = $this->name;
$search['rule_1_operator'] = 4;
- $search['rule_1'] = "artist";
- $albums = Search::run($search);
+ $search['rule_1'] = "artist";
+ $albums = Search::run($search);
$childrens = array();
foreach ($albums as $album) {
@@ -608,11 +621,11 @@ class Artist extends database_object implements library_item
public function display_art($thumb = 2)
{
- $id = null;
+ $id = null;
$type = null;
if (Art::has_db($this->id, 'artist')) {
- $id = $this->id;
+ $id = $this->id;
$type = 'artist';
}
@@ -627,12 +640,14 @@ class Artist extends database_object implements library_item
$user = $GLOBALS['user']->id;
}
- if (!$user)
+ if (!$user) {
return false;
+ }
if (AmpConfig::get('upload_allow_edit')) {
- if ($this->user !== null && $user == $this->user)
+ if ($this->user !== null && $user == $this->user) {
return true;
+ }
}
return Access::check('interface', 50, $user);
@@ -650,13 +665,18 @@ class Artist extends database_object implements library_item
public static function check($name, $mbid = null, $readonly = false)
{
$trimmed = Catalog::trim_prefix(trim($name));
- $name = $trimmed['string'];
- $prefix = $trimmed['prefix'];
+ $name = $trimmed['string'];
+ $prefix = $trimmed['prefix'];
+ // If Ampache support multiple artists per song one day, we should also handle other artists here
+ $trimmed = Catalog::trim_featuring($name);
+ $name = $trimmed[0];
- if ($mbid == '') $mbid = null;
+ if ($mbid == '') {
+ $mbid = null;
+ }
if (!$name) {
- $name = T_('Unknown (Orphaned)');
+ $name = T_('Unknown (Orphaned)');
$prefix = null;
}
@@ -664,26 +684,26 @@ class Artist extends database_object implements library_item
return self::$_mapcache[$name][$mbid];
}
- $id = 0;
+ $id = 0;
$exists = false;
if ($mbid) {
- $sql = 'SELECT `id` FROM `artist` WHERE `mbid` = ?';
+ $sql = 'SELECT `id` FROM `artist` WHERE `mbid` = ?';
$db_results = Dba::read($sql, array($mbid));
if ($row = Dba::fetch_assoc($db_results)) {
- $id = $row['id'];
+ $id = $row['id'];
$exists = true;
}
}
if (!$exists) {
- $sql = 'SELECT `id`, `mbid` FROM `artist` WHERE `name` LIKE ?';
+ $sql = 'SELECT `id`, `mbid` FROM `artist` WHERE `name` LIKE ?';
$db_results = Dba::read($sql, array($name));
$id_array = array();
while ($row = Dba::fetch_assoc($db_results)) {
- $key = $row['mbid'] ?: 'null';
+ $key = $row['mbid'] ?: 'null';
$id_array[$key] = $row['id'];
}
@@ -694,12 +714,12 @@ class Artist extends database_object implements library_item
Dba::write($sql, array($mbid, $id_array['null']));
}
if (isset($id_array['null'])) {
- $id = $id_array['null'];
+ $id = $id_array['null'];
$exists = true;
}
} else {
// Pick one at random
- $id = array_shift($id_array);
+ $id = array_shift($id_array);
$exists = true;
}
}
@@ -725,7 +745,6 @@ class Artist extends database_object implements library_item
self::$_mapcache[$name][$mbid] = $id;
return $id;
-
}
/**
@@ -737,11 +756,11 @@ class Artist extends database_object implements library_item
public function update(array $data)
{
// Save our current ID
- $name = isset($data['name']) ? $data['name'] : $this->name;
- $mbid = isset($data['mbid']) ? $data['mbid'] : $this->mbid;
- $summary = isset($data['summary']) ? $data['summary'] : $this->summary;
+ $name = isset($data['name']) ? $data['name'] : $this->name;
+ $mbid = isset($data['mbid']) ? $data['mbid'] : $this->mbid;
+ $summary = isset($data['summary']) ? $data['summary'] : $this->summary;
$placeformed = isset($data['placeformed']) ? $data['placeformed'] : $this->placeformed;
- $yearformed = isset($data['yearformed']) ? $data['yearformed'] : $this->yearformed;
+ $yearformed = isset($data['yearformed']) ? $data['yearformed'] : $this->yearformed;
$current_id = $this->id;
@@ -750,7 +769,7 @@ class Artist extends database_object implements library_item
$artist_id = self::check($name, $mbid, true);
$updated = false;
- $songs = array();
+ $songs = array();
// If it's changed we need to update
if ($artist_id != null && $artist_id != $this->id) {
@@ -758,7 +777,7 @@ class Artist extends database_object implements library_item
foreach ($songs as $song_id) {
Song::update_artist($artist_id,$song_id);
}
- $updated = true;
+ $updated = true;
$current_id = $artist_id;
Stats::migrate('artist', $this->id, $artist_id);
Art::migrate('artist', $this->id, $artist_id);
@@ -772,21 +791,24 @@ class Artist extends database_object implements library_item
Stats::gc();
Rating::gc();
Userflag::gc();
+ Useractivity::gc();
} // if updated
- } else if ($this->mbid != $mbid) {
- $sql = 'UPDATE `artist` SET `mbid` = ? WHERE `id` = ?';
- Dba::write($sql, array($mbid, $current_id));
+ } else {
+ if ($this->mbid != $mbid) {
+ $sql = 'UPDATE `artist` SET `mbid` = ? WHERE `id` = ?';
+ Dba::write($sql, array($mbid, $current_id));
+ }
}
// Update artist name (if we don't want to use the MusicBrainz name)
$trimmed = Catalog::trim_prefix(trim($name));
- $name = $trimmed['string'];
+ $name = $trimmed['string'];
if ($name != '' && $name != $this->name) {
$sql = 'UPDATE `artist` SET `name` = ? WHERE `id` = ?';
Dba::write($sql, array($name, $current_id));
}
- $this->update_artist_info($summary, $placeformed, $yearformed);
+ $this->update_artist_info($summary, $placeformed, $yearformed, true);
$this->name = $name;
$this->mbid = $mbid;
@@ -810,7 +832,6 @@ class Artist extends database_object implements library_item
}
return $current_id;
-
} // update
/**
@@ -845,14 +866,14 @@ class Artist extends database_object implements library_item
* @param int $yearformed
* @return boolean
*/
- public function update_artist_info($summary, $placeformed, $yearformed)
+ public function update_artist_info($summary, $placeformed, $yearformed, $manual = false)
{
- $sql = "UPDATE `artist` SET `summary` = ?, `placeformed` = ?, `yearformed` = ?, `last_update` = ? WHERE `id` = ?";
- $sqlret = Dba::write($sql, array($summary, $placeformed, $yearformed, time(), $this->id));
+ $sql = "UPDATE `artist` SET `summary` = ?, `placeformed` = ?, `yearformed` = ?, `last_update` = ?, `manual_update` = ? WHERE `id` = ?";
+ $sqlret = Dba::write($sql, array($summary, $placeformed, Catalog::normalize_year($yearformed), time(), $manual ? 1 : 0, $this->id));
- $this->summary = $summary;
+ $this->summary = $summary;
$this->placeformed = $placeformed;
- $this->yearformed = $yearformed;
+ $this->yearformed = $yearformed;
return $sqlret;
}
@@ -870,29 +891,30 @@ class Artist extends database_object implements library_item
public function remove_from_disk()
{
- $deleted = true;
+ $deleted = true;
$album_ids = $this->get_albums();
foreach ($album_ids as $id) {
- $album = new Album($id);
+ $album = new Album($id);
$deleted = $album->remove_from_disk();
if (!$deleted) {
- debug_event('artist', 'Error when deleting the album `' . $id .'`.', 1);
+ debug_event('artist', 'Error when deleting the album `' . $id . '`.', 1);
break;
}
}
if ($deleted) {
- $sql = "DELETE FROM `artist` WHERE `id` = ?";
+ $sql = "DELETE FROM `artist` WHERE `id` = ?";
$deleted = Dba::write($sql, array($this->id));
if ($deleted) {
Art::gc('artist', $this->id);
Userflag::gc('artist', $this->id);
Rating::gc('artist', $this->id);
Shoutbox::gc('artist', $this->id);
+ Useractivity::gc('artist', $this->id);
}
}
return $deleted;
}
-
} // end of artist class
+
diff --git a/sources/lib/class/artist_event.class.php b/sources/lib/class/artist_event.class.php
index 7b33a13..91dbabd 100644
--- a/sources/lib/class/artist_event.class.php
+++ b/sources/lib/class/artist_event.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -85,5 +85,5 @@ class Artist_Event
return false;
}
-
} // end of recommendation class
+
diff --git a/sources/lib/class/auth.class.php b/sources/lib/class/auth.class.php
index 3748b21..59d2f28 100644
--- a/sources/lib/class/auth.class.php
+++ b/sources/lib/class/auth.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -68,7 +68,7 @@ class Auth
xoutput_headers();
- $results = array();
+ $results = array();
$results['rfc3514'] = '';
echo xoutput_from_array($results);
} else {
@@ -100,7 +100,9 @@ class Auth
}
$results = self::$function_name($username, $password);
- if ($results['success'] || ($allow_ui && !empty($results['ui_required']))) { break; }
+ if ($results['success'] || ($allow_ui && !empty($results['ui_required']))) {
+ break;
+ }
}
return $results;
@@ -137,7 +139,7 @@ class Auth
private static function mysql_auth($username, $password)
{
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));
if ($row = Dba::fetch_assoc($db_results)) {
@@ -146,7 +148,7 @@ class Auth
// variations of the password. Increases collision chances, but
// doesn't break things.
// FIXME: Break things in the future.
- $hashed_password = array();
+ $hashed_password = array();
$hashed_password[] = hash('sha256', $password);
$hashed_password[] = hash('sha256',
Dba::escape(stripslashes(htmlspecialchars(strip_tags($password)))));
@@ -188,19 +190,19 @@ class Auth
$results = array();
if (!function_exists('pam_auth')) {
$results['success'] = false;
- $results['error'] = 'The PAM PHP module is not installed';
+ $results['error'] = 'The PAM PHP module is not installed';
return $results;
}
$password = scrub_in($password);
if (pam_auth($username, $password)) {
- $results['success'] = true;
- $results['type'] = 'pam';
+ $results['success'] = true;
+ $results['type'] = 'pam';
$results['username'] = $username;
} else {
$results['success'] = false;
- $results['error'] = 'PAM login attempt failed';
+ $results['error'] = 'PAM login attempt failed';
}
return $results;
@@ -234,7 +236,7 @@ class Auth
), $pipes);
if (is_resource($proc)) {
- fwrite($pipes[0], $username."\n".$password."\n");
+ fwrite($pipes[0], $username . "\n" . $password . "\n");
fclose($pipes[0]);
fclose($pipes[1]);
if ($stderr = fread($pipes[2], 8192)) {
@@ -301,18 +303,18 @@ class Auth
if (!($ldap_dn && $ldap_url && $ldap_filter && $ldap_class)) {
debug_event('ldap_auth', 'Required config value missing', 1);
$results['success'] = false;
- $results['error'] = 'Incomplete LDAP config';
+ $results['error'] = 'Incomplete LDAP config';
return $results;
}
- if (strpos($ldap_filter, "%v") >= 0) {
+ if (strpos($ldap_filter, "%v") !== false) {
$ldap_filter = str_replace("%v", $username, $ldap_filter);
} else {
// This to support previous configuration where only the fieldname was set
$ldap_filter = "($ldap_filter=$username)";
}
- $ldap_name_field = AmpConfig::get('ldap_name_field');
+ $ldap_name_field = AmpConfig::get('ldap_name_field');
$ldap_email_field = AmpConfig::get('ldap_email_field');
if ($ldap_link = ldap_connect($ldap_url) ) {
@@ -323,13 +325,13 @@ class Auth
// bind using our auth if we need to for initial search
if (!ldap_bind($ldap_link, $ldap_username, $ldap_password)) {
$results['success'] = false;
- $results['error'] = 'Could not bind to LDAP server.';
+ $results['error'] = 'Could not bind to LDAP server.';
return $results;
} // If bind fails
$searchstr = "(&(objectclass=$ldap_class)$ldap_filter)";
debug_event('ldap_auth', 'ldap_search: ' . $searchstr, 5);
- $sr = ldap_search($ldap_link, $ldap_dn, $searchstr);
+ $sr = ldap_search($ldap_link, $ldap_dn, $searchstr);
$info = ldap_get_entries($ldap_link, $sr);
if ($info["count"] == 1) {
@@ -348,7 +350,7 @@ class Auth
if (!$group_result) {
debug_event('ldap_auth', "Failure reading $require_group", 1);
$results['success'] = false;
- $results['error'] = 'The LDAP group could not be read';
+ $results['error'] = 'The LDAP group could not be read';
return $results;
}
@@ -357,7 +359,7 @@ class Auth
if ($group_info['count'] < 1) {
debug_event('ldap_auth', "No members found in $require_group", 1);
$results['success'] = false;
- $results['error'] = 'Empty LDAP group';
+ $results['error'] = 'Empty LDAP group';
return $results;
}
@@ -365,7 +367,7 @@ class Auth
if (!$group_match) {
debug_event('ldap_auth', "$user_dn is not a member of $require_group",1);
$results['success'] = false;
- $results['error'] = 'LDAP login attempt failed';
+ $results['error'] = 'LDAP login attempt failed';
return $results;
}
}
@@ -377,11 +379,8 @@ class Auth
$results['email'] = $info[0][$ldap_email_field][0];
return $results;
-
} // if we get something good back
-
} // if something was sent back
-
} // if failed connect
/* Default to bad news */
@@ -389,7 +388,6 @@ class Auth
$results['error'] = 'LDAP login attempt failed';
return $results;
-
} // ldap_auth
/**
@@ -406,11 +404,11 @@ class Auth
$results = array();
if (($_SERVER['REMOTE_USER'] == $username) ||
($_SERVER['HTTP_REMOTE_USER'] == $username)) {
- $results['success'] = true;
- $results['type'] = 'http';
+ $results['success'] = true;
+ $results['type'] = 'http';
$results['username'] = $username;
- $results['name'] = $username;
- $results['email'] = '';
+ $results['name'] = $username;
+ $results['email'] = '';
} else {
$results['success'] = false;
$results['error'] = 'HTTP auth login attempt failed';
@@ -468,7 +466,7 @@ class Auth
}
} else {
// Generate form markup and render it.
- $form_id = 'openid_message';
+ $form_id = 'openid_message';
$form_html = $auth_request->htmlMarkup(AmpConfig::get('web_path'), Openid::get_return_url(), false, array('id' => $form_id));
if (Auth_OpenID::isFailure($form_html)) {
@@ -477,15 +475,15 @@ class Auth
} else {
debug_event('auth', 'OpenID 2: javascript redirection code to OpenID form.', '5');
// First step is a success, UI interaction required.
- $results['success'] = false;
+ $results['success'] = false;
$results['ui_required'] = $form_html;
}
}
- } else {
+ } else {
debug_event('auth', $website . ' is not a valid OpenID.', '3');
$results['success'] = false;
$results['error'] = 'Not a valid OpenID.';
- }
+ }
} else {
debug_event('auth', 'Cannot initialize OpenID resources.', '3');
$results['success'] = false;
@@ -507,62 +505,66 @@ class Auth
*/
private static function openid_auth_2()
{
- $results = array();
+ $results = array();
$results['type'] = 'openid';
- $consumer = Openid::get_consumer();
+ $consumer = Openid::get_consumer();
if ($consumer) {
$response = $consumer->complete(Openid::get_return_url());
if ($response->status == Auth_OpenID_CANCEL) {
$results['success'] = false;
$results['error'] = 'OpenID verification cancelled.';
- } else if ($response->status == Auth_OpenID_FAILURE) {
- $results['success'] = false;
- $results['error'] = 'OpenID authentication failed: ' . $response->message;
- } else if ($response->status == Auth_OpenID_SUCCESS) {
- // Extract the identity URL and Simple Registration data (if it was returned).
- $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response);
- $sreg = $sreg_resp->contents();
+ } else {
+ if ($response->status == Auth_OpenID_FAILURE) {
+ $results['success'] = false;
+ $results['error'] = 'OpenID authentication failed: ' . $response->message;
+ } else {
+ if ($response->status == Auth_OpenID_SUCCESS) {
+ // Extract the identity URL and Simple Registration data (if it was returned).
+ $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response);
+ $sreg = $sreg_resp->contents();
- $results['website'] = $response->getDisplayIdentifier();
- if (@$sreg['email']) {
- $results['email'] = $sreg['email'];
- }
+ $results['website'] = $response->getDisplayIdentifier();
+ if (@$sreg['email']) {
+ $results['email'] = $sreg['email'];
+ }
- if (@$sreg['nickname']) {
- $results['username'] = $sreg['nickname'];
- }
+ if (@$sreg['nickname']) {
+ $results['username'] = $sreg['nickname'];
+ }
- if (@$sreg['fullname']) {
- $results['name'] = $sreg['fullname'];
- }
+ if (@$sreg['fullname']) {
+ $results['name'] = $sreg['fullname'];
+ }
- $users = User::get_from_website($results['website']);
- if (count($users) > 0) {
- if (count($users) == 1) {
- $user = new User($users[0]);
- $results['success'] = true;
- $results['username'] = $user->username;
- } else {
- // Several users for the same website/openid? Allowed but stupid, try to get a match on username.
+ $users = User::get_from_website($results['website']);
+ if (count($users) > 0) {
+ if (count($users) == 1) {
+ $user = new User($users[0]);
+ $results['success'] = true;
+ $results['username'] = $user->username;
+ } else {
+ // Several users for the same website/openid? Allowed but stupid, try to get a match on username.
// Should we make website field unique?
foreach ($users as $id) {
$user = new User($id);
if ($user->username == $results['username']) {
- $results['success'] = true;
+ $results['success'] = true;
$results['username'] = $user->username;
}
}
- }
- } else {
- // Don't return success if an user already exists for this username but don't have this openid identity as website
+ }
+ } else {
+ // Don't return success if an user already exists for this username but don't have this openid identity as website
$user = User::get_from_username($results['username']);
- if ($user->id) {
- $results['success'] = false;
- $results['error'] = 'No user associated to this OpenID and username already taken.';
- } else {
- $results['success'] = true;
- $results['error'] = 'No user associated to this OpenID.';
+ if ($user->id) {
+ $results['success'] = false;
+ $results['error'] = 'No user associated to this OpenID and username already taken.';
+ } else {
+ $results['success'] = true;
+ $results['error'] = 'No user associated to this OpenID.';
+ }
+ }
}
}
}
diff --git a/sources/lib/class/autoupdate.class.php b/sources/lib/class/autoupdate.class.php
index c114820..7ed3921 100644
--- a/sources/lib/class/autoupdate.class.php
+++ b/sources/lib/class/autoupdate.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -45,7 +45,7 @@ class AutoUpdate
protected static function is_develop()
{
$version = AmpConfig::get('version');
- $vspart = explode('-', $version);
+ $vspart = explode('-', $version);
return ($vspart[count($vspart) - 1] == 'develop');
}
@@ -77,7 +77,7 @@ class AutoUpdate
{
try {
// https is mandatory
- $url = "https://api.github.com/repos/ampache/ampache" . $action;
+ $url = "https://api.github.com/repos/ampache/ampache" . $action;
$request = Requests::get($url, array(), Core::requests_options());
// Not connected / API rate limit exceeded: just ignore, it will pass next time
@@ -195,8 +195,8 @@ class AutoUpdate
debug_event('autoupdate', 'Checking latest version online...', '5');
$available = false;
- $current = self::get_current_version();
- $latest = self::get_latest_version();
+ $current = self::get_current_version();
+ $latest = self::get_latest_version();
if ($current != $latest && !empty($current)) {
if (self::is_develop()) {
@@ -243,12 +243,27 @@ class AutoUpdate
*/
public static function update_files()
{
- echo T_('Updating Ampache sources with `git pull` ...') . ' ';
+ $cmd = 'git pull https://github.com/ampache/ampache.git';
+ echo T_('Updating Ampache sources with `' . $cmd . '` ...') . ' ';
ob_flush();
chdir(AmpConfig::get('prefix'));
- exec('git pull https://github.com/ampache/ampache.git');
+ exec($cmd);
echo T_('Done') . ' ';
ob_flush();
self::get_latest_version(true);
}
+
+ /**
+ * Update project dependencies.
+ */
+ public static function update_dependencies()
+ {
+ $cmd = 'composer install --prefer-source --no-interaction';
+ echo T_('Updating dependencies with `' . $cmd . '` ...') . ' ';
+ ob_flush();
+ chdir(AmpConfig::get('prefix'));
+ exec($cmd);
+ echo T_('Done') . ' ';
+ ob_flush();
+ }
}
diff --git a/sources/lib/class/bookmark.class.php b/sources/lib/class/bookmark.class.php
new file mode 100644
index 0000000..cd0cb00
--- /dev/null
+++ b/sources/lib/class/bookmark.class.php
@@ -0,0 +1,156 @@
+.
+ *
+ */
+
+/**
+ * Bookmark class
+ *
+ * This manage bookmark on playable items
+ *
+ */
+class Bookmark extends database_object
+{
+ // Public variables
+ public $id;
+ public $user;
+ public $object_id;
+ public $object_type;
+ public $position;
+ public $comment;
+ public $creation_date;
+ public $update_date;
+
+ public $f_user;
+
+ /**
+ * Constructor
+ * This is run every time a new object is created, and requires
+ * the id and type of object that we need to pull for
+ */
+ public function __construct ($object_id, $object_type = null, $user_id = null)
+ {
+ if (!$object_id) {
+ return false;
+ }
+
+ if (!$object_type) {
+ $info = $this->get_info($object_id);
+ } else {
+ if ($user_id == null) {
+ $user_id = $GLOBALS['user']->id;
+ }
+
+ $sql = "SELECT * FROM `bookmark` WHERE `object_type` = ? AND `object_id` = ? AND `user` = ?";
+ $db_results = Dba::read($sql, array($object_type, $object_id, $user_id));
+
+ if (!$db_results) {
+ return false;
+ }
+
+ $info = Dba::fetch_assoc($db_results);
+ }
+
+ // Foreach what we've got
+ foreach ($info as $key=>$value) {
+ $this->$key = $value;
+ }
+
+ return true;
+ }
+
+ /**
+ * gc
+ *
+ * Remove bookmark for items that no longer exist.
+ */
+ public static function gc($object_type = null, $object_id = null)
+ {
+ $types = array('song', 'video', 'podcast_episode');
+
+ if ($object_type != null) {
+ if (in_array($object_type, $types)) {
+ $sql = "DELETE FROM `bookmark` WHERE `object_type` = ? AND `object_id` = ?";
+ Dba::write($sql, array($object_type, $object_id));
+ } else {
+ debug_event('bookmark', 'Garbage collect on type `' . $object_type . '` is not supported.', 1);
+ }
+ } else {
+ foreach ($types as $type) {
+ Dba::write("DELETE FROM `bookmark` USING `bookmark` LEFT JOIN `$type` ON `$type`.`id` = `bookmark`.`object_id` WHERE `bookmark`.`object_type` = '$type' AND `$type`.`id` IS NULL");
+ }
+ }
+ }
+
+ public static function get_bookmarks_ids($user = null)
+ {
+ $ids = array();
+ if ($user == null) {
+ $user = $GLOBALS['user'];
+ }
+
+ $sql = "SELECT `id` FROM `bookmark` WHERE `user` = ?";
+ $db_results = Dba::read($sql, array($user->id));
+ while ($results = Dba::fetch_assoc($db_results)) {
+ $ids[] = $results['id'];
+ }
+
+ return $ids;
+ }
+
+ public static function get_bookmarks($user = null)
+ {
+ $bookmarks = array();
+ $ids = self::get_bookmarks_ids($user);
+ foreach ($ids as $id) {
+ $bookmarks[] = new Bookmark($id);
+ }
+ return $bookmarks;
+ }
+
+ public static function create(array $data)
+ {
+ $user = $data['user'] ?: $GLOBALS['user']->id;
+ $position = $data['position'] ?: 0;
+ $comment = scrub_in($data['comment']);
+
+ $sql = "INSERT INTO `bookmark` (`user`, `position`, `comment`, `object_type`, `object_id`, `creation_date`, `update_date`) VALUES (?, ?, ?, ?, ?, ?, ?)";
+ return Dba::write($sql, array($user, $position, $comment, $data['object_type'], $data['object_id'], time(), time()));
+ }
+
+ public function update($position)
+ {
+ $sql = "UPDATE `bookmark` SET `position` = ?, `update_date` = ? WHERE `id` = ?";
+ return Dba::write($sql, array($position, time(), $this->id));
+ }
+
+ public function remove()
+ {
+ $sql = "DELETE FROM `bookmark` WHERE `id` = ?";
+ return Dba::write($sql, array($this->id));
+ }
+
+ public function format()
+ {
+ $user = new User($this->user);
+ $f_user = $user->username;
+ }
+} //end bookmark class
+
diff --git a/sources/lib/class/broadcast.class.php b/sources/lib/class/broadcast.class.php
index 56669cc..ba05fc2 100644
--- a/sources/lib/class/broadcast.class.php
+++ b/sources/lib/class/broadcast.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -78,7 +78,9 @@ class Broadcast extends database_object implements library_item
*/
public function __construct($id=0)
{
- if (!$id) { return true; }
+ if (!$id) {
+ return true;
+ }
/* Get the information from the db */
$info = $this->get_info($id);
@@ -125,7 +127,7 @@ class Broadcast extends database_object implements library_item
$sql = "UPDATE `broadcast` SET `song` = ? " .
"WHERE `id` = ?";
Dba::write($sql, array($song_id, $this->id));
- $this->song = $song_id;
+ $this->song = $song_id;
$this->song_position = 0;
}
@@ -148,7 +150,7 @@ class Broadcast extends database_object implements library_item
public static function create($name, $description='')
{
if (!empty($name)) {
- $sql = "INSERT INTO `broadcast` (`user`, `name`, `description`, `is_private`) VALUES (?, ?, ?, '1')";
+ $sql = "INSERT INTO `broadcast` (`user`, `name`, `description`, `is_private`) VALUES (?, ?, ?, '1')";
$params = array($GLOBALS['user']->id, $name, $description);
Dba::write($sql, $params);
return Dba::insert_id();
@@ -181,7 +183,7 @@ class Broadcast extends database_object implements library_item
$this->f_name = $this->name;
$this->f_link = '' . scrub_out($this->f_name) . '';
if ($details) {
- $this->tags = Tag::get_top_tags('broadcast', $this->id);
+ $this->tags = Tag::get_top_tags('broadcast', $this->id);
$this->f_tags = Tag::get_display($this->tags, true, 'broadcast');
}
}
@@ -308,9 +310,9 @@ class Broadcast extends database_object implements library_item
*/
public static function get_broadcast_list()
{
- $sql = self::get_broadcast_list_sql();
+ $sql = self::get_broadcast_list_sql();
$db_results = Dba::read($sql);
- $results = array();
+ $results = array();
while ($row = Dba::fetch_assoc($db_results)) {
$results[] = $row['id'];
@@ -336,7 +338,7 @@ class Broadcast extends database_object implements library_item
*/
public static function get_broadcast($key)
{
- $sql = "SELECT `id` FROM `broadcast` WHERE `key` = ?";
+ $sql = "SELECT `id` FROM `broadcast` WHERE `key` = ?";
$db_results = Dba::read($sql, array($key));
if ($results = Dba::fetch_assoc($db_results)) {
@@ -354,7 +356,7 @@ class Broadcast extends database_object implements library_item
if ($this->id) {
if ($GLOBALS['user']->has_access('75')) {
echo "id . "\" onclick=\"showEditDialog('broadcast_row', '" . $this->id . "', 'edit_broadcast_" . $this->id . "', '" . T_('Broadcast edit') . "', 'broadcast_row_')\">" . UI::get_icon('edit', T_('Edit')) . "";
- echo " id ."\">" . UI::get_icon('delete', T_('Delete')) . "";
+ echo " id . "\">" . UI::get_icon('delete', T_('Delete')) . "";
}
}
}
@@ -392,7 +394,7 @@ class Broadcast extends database_object implements library_item
*/
public static function get_broadcasts($user_id)
{
- $sql = "SELECT `id` FROM `broadcast` WHERE `user` = ?";
+ $sql = "SELECT `id` FROM `broadcast` WHERE `user` = ?";
$db_results = Dba::read($sql, array($user_id));
$broadcasts = array();
@@ -404,7 +406,6 @@ class Broadcast extends database_object implements library_item
public static function gc()
{
-
}
/*
@@ -421,5 +422,5 @@ class Broadcast extends database_object implements library_item
{
return $oid;
}
-
} // end of broadcast class
+
diff --git a/sources/lib/class/broadcast_server.class.php b/sources/lib/class/broadcast_server.class.php
index bd1d558..1df08e4 100644
--- a/sources/lib/class/broadcast_server.class.php
+++ b/sources/lib/class/broadcast_server.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -25,15 +25,15 @@ use Ratchet\ConnectionInterface;
class Broadcast_Server implements MessageComponentInterface
{
- const BROADCAST_SONG = "SONG";
- const BROADCAST_SONG_POSITION = "SONG_POSITION";
- const BROADCAST_PLAYER_PLAY = "PLAYER_PLAY";
+ const BROADCAST_SONG = "SONG";
+ const BROADCAST_SONG_POSITION = "SONG_POSITION";
+ const BROADCAST_PLAYER_PLAY = "PLAYER_PLAY";
const BROADCAST_REGISTER_BROADCAST = "REGISTER_BROADCAST";
- const BROADCAST_REGISTER_LISTENER = "REGISTER_LISTENER";
- const BROADCAST_ENDED = "ENDED";
- const BROADCAST_INFO = "INFO";
- const BROADCAST_NB_LISTENERS = "NB_LISTENERS";
- const BROADCAST_AUTH_SID = "AUTH_SID";
+ const BROADCAST_REGISTER_LISTENER = "REGISTER_LISTENER";
+ const BROADCAST_ENDED = "ENDED";
+ const BROADCAST_INFO = "INFO";
+ const BROADCAST_NB_LISTENERS = "NB_LISTENERS";
+ const BROADCAST_AUTH_SID = "AUTH_SID";
public $verbose;
/**
@@ -55,10 +55,10 @@ class Broadcast_Server implements MessageComponentInterface
public function __construct()
{
- $this->verbose = false;
- $this->clients = array();
- $this->sids = array();
- $this->listeners = array();
+ $this->verbose = false;
+ $this->clients = array();
+ $this->sids = array();
+ $this->listeners = array();
$this->broadcasters = array();
}
@@ -109,13 +109,13 @@ class Broadcast_Server implements MessageComponentInterface
break;
default:
if ($this->verbose) {
- echo "[" . time() ."][warning]Unknown message code." . "\r\n";
+ echo "[" . time() . "][warning]Unknown message code." . "\r\n";
}
break;
}
} else {
if ($this->verbose) {
- echo "[" . time() ."][error]Wrong message format (" . $command . ")." . "\r\n";
+ echo "[" . time() . "][error]Wrong message format (" . $command . ")." . "\r\n";
}
}
}
@@ -129,7 +129,7 @@ class Broadcast_Server implements MessageComponentInterface
*/
protected function getSongJS($song_id)
{
- $media = array();
+ $media = array();
$media[] = array(
'object_type' => 'song',
'object_id' => $song_id
@@ -148,7 +148,7 @@ class Broadcast_Server implements MessageComponentInterface
{
if ($this->isBroadcaster($from)) {
$broadcast = $this->broadcasters[$from->resourceId];
- $clients = $this->getListeners($broadcast);
+ $clients = $this->getListeners($broadcast);
Session::extend(Stream::get_session(), 'stream');
@@ -156,7 +156,7 @@ class Broadcast_Server implements MessageComponentInterface
$this->broadcastMessage($clients, self::BROADCAST_SONG, base64_encode($this->getSongJS($song_id)));
if ($this->verbose) {
- echo "[" . time() ."][info]Broadcast " . $broadcast->id . " now playing song " . $song_id . "." . "\r\n";
+ echo "[" . time() . "][info]Broadcast " . $broadcast->id . " now playing song " . $song_id . "." . "\r\n";
}
} else {
debug_event('broadcast', 'Action unauthorized.', '3');
@@ -172,7 +172,7 @@ class Broadcast_Server implements MessageComponentInterface
{
if ($this->isBroadcaster($from)) {
$broadcast = $this->broadcasters[$from->resourceId];
- $seekdiff = $broadcast->song_position - $song_position;
+ $seekdiff = $broadcast->song_position - $song_position;
if ($seekdiff > 2 || $seekdiff < -2) {
$clients = $this->getListeners($broadcast);
$this->broadcastMessage($clients, self::BROADCAST_SONG_POSITION, $song_position);
@@ -180,7 +180,7 @@ class Broadcast_Server implements MessageComponentInterface
$broadcast->song_position = $song_position;
if ($this->verbose) {
- echo "[" . time() ."][info]Broadcast " . $broadcast->id . " has song position to " . $song_position . "." . "\r\n";
+ echo "[" . time() . "][info]Broadcast " . $broadcast->id . " has song position to " . $song_position . "." . "\r\n";
}
} else {
debug_event('broadcast', 'Action unauthorized.', '3');
@@ -196,11 +196,11 @@ class Broadcast_Server implements MessageComponentInterface
{
if ($this->isBroadcaster($from)) {
$broadcast = $this->broadcasters[$from->resourceId];
- $clients = $this->getListeners($broadcast);
+ $clients = $this->getListeners($broadcast);
$this->broadcastMessage($clients, self::BROADCAST_PLAYER_PLAY, $play ? 'true' : 'false');
if ($this->verbose) {
- echo "[" . time() ."][info]Broadcast " . $broadcast->id . " player state: " . $play . "." . "\r\n";
+ echo "[" . time() . "][info]Broadcast " . $broadcast->id . " player state: " . $play . "." . "\r\n";
}
} else {
debug_event('broadcast', 'Action unauthorized.', '3');
@@ -215,11 +215,11 @@ class Broadcast_Server implements MessageComponentInterface
{
if ($this->isBroadcaster($from)) {
$broadcast = $this->broadcasters[$from->resourceId];
- $clients = $this->getListeners($broadcast);
+ $clients = $this->getListeners($broadcast);
$this->broadcastMessage($clients, self::BROADCAST_ENDED);
if ($this->verbose) {
- echo "[" . time() ."][info]Broadcast " . $broadcast->id . " ended." . "\r\n";
+ echo "[" . time() . "][info]Broadcast " . $broadcast->id . " ended." . "\r\n";
}
} else {
debug_event('broadcast', 'Action unauthorized.', '3');
@@ -236,7 +236,7 @@ class Broadcast_Server implements MessageComponentInterface
$broadcast = Broadcast::get_broadcast($broadcast_key);
if ($broadcast) {
$this->broadcasters[$from->resourceId] = $broadcast;
- $this->listeners[$broadcast->id] = array();
+ $this->listeners[$broadcast->id] = array();
if ($this->verbose) {
echo "[info]Broadcast " . $broadcast->id . " registered." . "\r\n";
@@ -251,7 +251,7 @@ class Broadcast_Server implements MessageComponentInterface
protected function unregisterBroadcast(ConnectionInterface $conn)
{
$broadcast = $this->broadcasters[$conn->resourceId];
- $clients = $this->getListeners($broadcast);
+ $clients = $this->getListeners($broadcast);
$this->broadcastMessage($clients, self::BROADCAST_ENDED);
$broadcast->update_state(false);
@@ -259,7 +259,7 @@ class Broadcast_Server implements MessageComponentInterface
unset($this->broadcasters[$conn->resourceId]);
if ($this->verbose) {
- echo "[" . time() ."][info]Broadcast " . $broadcast->id . " unregistered." . "\r\n";
+ echo "[" . time() . "][info]Broadcast " . $broadcast->id . " unregistered." . "\r\n";
}
}
@@ -353,8 +353,8 @@ class Broadcast_Server implements MessageComponentInterface
{
$broadcaster_id = array_search($broadcast, $this->broadcasters);
if ($broadcaster_id) {
- $clients = $this->listeners[$broadcast->id];
- $clients[] = $this->clients[$broadcaster_id];
+ $clients = $this->listeners[$broadcast->id];
+ $clients[] = $this->clients[$broadcaster_id];
$nb_listeners = count($this->listeners[$broadcast->id]);
$broadcast->update_listeners($nb_listeners);
$this->broadcastMessage($clients, self::BROADCAST_NB_LISTENERS, $nb_listeners);
@@ -433,10 +433,10 @@ class Broadcast_Server implements MessageComponentInterface
{
$websocket_address = AmpConfig::get('websocket_address');
if (empty($websocket_address)) {
- $websocket_address = 'ws://' . $_SERVER['HTTP_HOST'] . ':8100';
+ $websocket_address = 'ws://' . $_SERVER['SERVER_NAME'] . ':8100';
}
return $websocket_address . '/broadcast';
}
-
} // end of broadcast_server class
+
diff --git a/sources/lib/class/browse.class.php b/sources/lib/class/browse.class.php
index 459873c..e8a951b 100644
--- a/sources/lib/class/browse.class.php
+++ b/sources/lib/class/browse.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -49,6 +49,7 @@ class Browse extends Query
if (!$id) {
$this->set_use_pages(true);
$this->set_use_alpha(false);
+ $this->set_grid_view(true);
}
$this->show_header = true;
}
@@ -63,7 +64,6 @@ class Browse extends Query
public function set_simple_browse($value)
{
$this->set_is_simple($value);
-
} // set_simple_browse
/**
@@ -78,7 +78,6 @@ class Browse extends Query
$_SESSION['browse']['supplemental'][$this->id][$class] = intval($uid);
return true;
-
} // add_supplemental_object
/**
@@ -97,7 +96,6 @@ class Browse extends Query
}
return $objects;
-
} // get_supplemental_objects
/**
@@ -113,7 +111,6 @@ class Browse extends Query
// Checking if value is suitable
$start = $_SESSION[$name]['start'];
if ($this->get_offset() > 0) {
-
$set_page = floor($start / $this->get_offset());
if ($this->get_total() > $this->get_offset()) {
$total_pages = ceil($this->get_total() / $this->get_offset());
@@ -155,13 +152,15 @@ class Browse extends Query
$this->get_offset(),
true
);
- } else if (!count($object_ids)) {
- $this->set_total(0);
+ } else {
+ if (!count($object_ids)) {
+ $this->set_total(0);
+ }
}
// Load any additional object we need for this
$extra_objects = $this->get_supplemental_objects();
- $browse = $this;
+ $browse = $this;
foreach ($extra_objects as $class_name => $id) {
${$class_name} = new $class_name($id);
@@ -180,7 +179,7 @@ class Browse extends Query
} elseif ($filter_value = $this->get_filter('catalog')) {
// Get the catalog title
$catalog = Catalog::create_from_id(intval($filter_value));
- $match = ' (' . $catalog->name . ')';
+ $match = ' (' . $catalog->name . ')';
}
$type = $this->get_type();
@@ -195,7 +194,7 @@ class Browse extends Query
$argument_param = ($argument ? '&argument=' . scrub_in($argument) : '');
- debug_event('browse', 'Show objects called for type {'.$type.'}', '5');
+ debug_event('browse', 'Show objects called for type {' . $type . '}', '5');
$limit_threshold = $this->get_threshold();
@@ -204,7 +203,7 @@ class Browse extends Query
case 'song':
$box_title = T_('Songs') . $match;
Song::build_cache($object_ids, $limit_threshold);
- $box_req = AmpConfig::get('prefix') . '/templates/show_songs.inc.php';
+ $box_req = AmpConfig::get('prefix') . UI::find_template('show_songs.inc.php');
break;
case 'album':
Album::build_cache($object_ids);
@@ -217,122 +216,130 @@ class Browse extends Query
} else {
$allow_group_disks = false;
}
- $box_req = AmpConfig::get('prefix') . '/templates/show_albums.inc.php';
+ $box_req = AmpConfig::get('prefix') . UI::find_template('show_albums.inc.php');
break;
case 'user':
$box_title = T_('Users') . $match;
- $box_req = AmpConfig::get('prefix') . '/templates/show_users.inc.php';
+ $box_req = AmpConfig::get('prefix') . UI::find_template('show_users.inc.php');
break;
case 'artist':
$box_title = T_('Artists') . $match;
Artist::build_cache($object_ids, true, $limit_threshold);
- $box_req = AmpConfig::get('prefix') . '/templates/show_artists.inc.php';
+ $box_req = AmpConfig::get('prefix') . UI::find_template('show_artists.inc.php');
break;
case 'live_stream':
- require_once AmpConfig::get('prefix') . '/templates/show_live_stream.inc.php';
+ require_once AmpConfig::get('prefix') . UI::find_template('show_live_stream.inc.php');
$box_title = T_('Radio Stations') . $match;
- $box_req = AmpConfig::get('prefix') . '/templates/show_live_streams.inc.php';
+ $box_req = AmpConfig::get('prefix') . UI::find_template('show_live_streams.inc.php');
break;
case 'playlist':
Playlist::build_cache($object_ids);
$box_title = T_('Playlists') . $match;
- $box_req = AmpConfig::get('prefix') . '/templates/show_playlists.inc.php';
+ $box_req = AmpConfig::get('prefix') . UI::find_template('show_playlists.inc.php');
break;
- case 'playlist_song':
- $box_title = T_('Playlist Songs') . $match;
- $box_req = AmpConfig::get('prefix') . '/templates/show_playlist_songs.inc.php';
+ case 'playlist_media':
+ $box_title = T_('Playlist Medias') . $match;
+ $box_req = AmpConfig::get('prefix') . UI::find_template('show_playlist_medias.inc.php');
break;
case 'playlist_localplay':
$box_title = T_('Current Playlist');
- $box_req = AmpConfig::get('prefix') . '/templates/show_localplay_playlist.inc.php';
+ $box_req = AmpConfig::get('prefix') . UI::find_template('show_localplay_playlist.inc.php');
UI::show_box_bottom();
break;
case 'smartplaylist':
$box_title = T_('Smart Playlists') . $match;
- $box_req = AmpConfig::get('prefix') . '/templates/show_searches.inc.php';
+ $box_req = AmpConfig::get('prefix') . UI::find_template('show_searches.inc.php');
break;
case 'catalog':
$box_title = T_('Catalogs');
- $box_req = AmpConfig::get('prefix') . '/templates/show_catalogs.inc.php';
+ $box_req = AmpConfig::get('prefix') . UI::find_template('show_catalogs.inc.php');
break;
case 'shoutbox':
$box_title = T_('Shoutbox Records');
- $box_req = AmpConfig::get('prefix') . '/templates/show_manage_shoutbox.inc.php';
+ $box_req = AmpConfig::get('prefix') . UI::find_template('show_manage_shoutbox.inc.php');
break;
case 'tag':
Tag::build_cache($object_ids);
$box_title = T_('Tag Cloud');
- $box_req = AmpConfig::get('prefix') . '/templates/show_tagcloud.inc.php';
+ $box_req = AmpConfig::get('prefix') . UI::find_template('show_tagcloud.inc.php');
break;
case 'video':
Video::build_cache($object_ids);
$video_type = 'video';
- $box_title = T_('Videos');
- $box_req = AmpConfig::get('prefix') . '/templates/show_videos.inc.php';
+ $box_title = T_('Videos');
+ $box_req = AmpConfig::get('prefix') . UI::find_template('show_videos.inc.php');
break;
case 'democratic':
$box_title = T_('Democratic Playlist');
- $box_req = AmpConfig::get('prefix') . '/templates/show_democratic_playlist.inc.php';
+ $box_req = AmpConfig::get('prefix') . UI::find_template('show_democratic_playlist.inc.php');
break;
case 'wanted':
$box_title = T_('Wanted Albums');
- $box_req = AmpConfig::get('prefix') . '/templates/show_wanted_albums.inc.php';
+ $box_req = AmpConfig::get('prefix') . UI::find_template('show_wanted_albums.inc.php');
break;
case 'share':
$box_title = T_('Shared Objects');
- $box_req = AmpConfig::get('prefix') . '/templates/show_shared_objects.inc.php';
+ $box_req = AmpConfig::get('prefix') . UI::find_template('show_shared_objects.inc.php');
break;
case 'song_preview':
$box_title = T_('Songs');
- $box_req = AmpConfig::get('prefix') . '/templates/show_song_previews.inc.php';
+ $box_req = AmpConfig::get('prefix') . UI::find_template('show_song_previews.inc.php');
break;
case 'channel':
$box_title = T_('Channels');
- $box_req = AmpConfig::get('prefix') . '/templates/show_channels.inc.php';
+ $box_req = AmpConfig::get('prefix') . UI::find_template('show_channels.inc.php');
break;
case 'broadcast':
$box_title = T_('Broadcasts');
- $box_req = AmpConfig::get('prefix') . '/templates/show_broadcasts.inc.php';
+ $box_req = AmpConfig::get('prefix') . UI::find_template('show_broadcasts.inc.php');
break;
case 'license':
$box_title = T_('Media Licenses');
- $box_req = AmpConfig::get('prefix') . '/templates/show_manage_license.inc.php';
+ $box_req = AmpConfig::get('prefix') . UI::find_template('show_manage_license.inc.php');
break;
case 'tvshow':
$box_title = T_('TV Shows');
- $box_req = AmpConfig::get('prefix') . '/templates/show_tvshows.inc.php';
+ $box_req = AmpConfig::get('prefix') . UI::find_template('show_tvshows.inc.php');
break;
case 'tvshow_season':
$box_title = T_('Seasons');
- $box_req = AmpConfig::get('prefix') . '/templates/show_tvshow_seasons.inc.php';
+ $box_req = AmpConfig::get('prefix') . UI::find_template('show_tvshow_seasons.inc.php');
break;
case 'tvshow_episode':
- $box_title = T_('Episodes');
+ $box_title = T_('Episodes');
$video_type = $type;
- $box_req = AmpConfig::get('prefix') . '/templates/show_videos.inc.php';
+ $box_req = AmpConfig::get('prefix') . UI::find_template('show_videos.inc.php');
break;
case 'movie':
- $box_title = T_('Movies');
+ $box_title = T_('Movies');
$video_type = $type;
- $box_req = AmpConfig::get('prefix') . '/templates/show_videos.inc.php';
+ $box_req = AmpConfig::get('prefix') . UI::find_template('show_videos.inc.php');
break;
case 'clip':
- $box_title = T_('Clips');
+ $box_title = T_('Clips');
$video_type = $type;
- $box_req = AmpConfig::get('prefix') . '/templates/show_videos.inc.php';
+ $box_req = AmpConfig::get('prefix') . UI::find_template('show_videos.inc.php');
break;
case 'personal_video':
- $box_title = T_('Personal Videos');
+ $box_title = T_('Personal Videos');
$video_type = $type;
- $box_req = AmpConfig::get('prefix') . '/templates/show_videos.inc.php';
+ $box_req = AmpConfig::get('prefix') . UI::find_template('show_videos.inc.php');
break;
case 'label':
$box_title = T_('Labels');
- $box_req = AmpConfig::get('prefix') . '/templates/show_labels.inc.php';
+ $box_req = AmpConfig::get('prefix') . UI::find_template('show_labels.inc.php');
break;
case 'pvmsg':
$box_title = T_('Private Messages');
- $box_req = AmpConfig::get('prefix') . '/templates/show_pvmsgs.inc.php';
+ $box_req = AmpConfig::get('prefix') . UI::find_template('show_pvmsgs.inc.php');
+ break;
+ case 'podcast':
+ $box_title = T_('Podcasts');
+ $box_req = AmpConfig::get('prefix') . UI::find_template('show_podcasts.inc.php');
+ break;
+ case 'podcast_episode':
+ $box_title = T_('Podcast Episodes');
+ $box_req = AmpConfig::get('prefix') . UI::find_template('show_podcast_episodes.inc.php');
break;
default:
// Rien a faire
@@ -363,17 +370,16 @@ class Browse extends Query
}
}
Ajax::end_container();
-
} // show_object
public function show_next_link($argument = null)
{
- $limit = $this->get_offset();
- $start = $this->get_start();
- $total = $this->get_total();
+ $limit = $this->get_offset();
+ $start = $this->get_start();
+ $total = $this->get_total();
$next_offset = $start + $limit;
if ($next_offset <= $total) {
- echo '' . T_('More') . '';
+ echo '' . T_('More') . '';
}
}
@@ -387,7 +393,7 @@ class Browse extends Query
foreach ($request as $key => $value) {
//reinterpret v as a list of int
$list = explode(',', $value);
- $ok = true;
+ $ok = true;
foreach ($list as $item) {
if (!is_numeric($item)) {
$ok = false;
@@ -426,6 +432,10 @@ class Browse extends Query
$this->set_filter('regex_not_match', '');
}
}
+ $cn = 'browse_' . $type . '_grid_view';
+ if (isset($_COOKIE[$cn])) {
+ $this->set_grid_view($_COOKIE[$cn] == 'true');
+ }
parent::set_type($type, $custom_base);
}
@@ -460,6 +470,25 @@ class Browse extends Query
{
return $this->_state['use_pages'];
}
+
+ /**
+ *
+ * @param boolean $grid_view
+ */
+ public function set_grid_view($grid_view)
+ {
+ $this->save_cookie_params('grid_view', $grid_view ? 'true' : 'false');
+ $this->_state['grid_view'] = $grid_view;
+ }
+
+ /**
+ *
+ * @return boolean
+ */
+ public function get_grid_view()
+ {
+ return $this->_state['grid_view'];
+ }
/**
*
@@ -533,5 +562,18 @@ class Browse extends Query
{
return $this->_state['threshold'];
}
-
+
+ /**
+ *
+ * @return string
+ */
+ public function get_css_class()
+ {
+ $css = '';
+ if (!$this->_state['grid_view']) {
+ $css = 'disablegv';
+ }
+ return $css;
+ }
} // browse
+
diff --git a/sources/lib/class/catalog.class.php b/sources/lib/class/catalog.class.php
index 0090bf8..66acc5c 100644
--- a/sources/lib/class/catalog.class.php
+++ b/sources/lib/class/catalog.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -196,7 +196,7 @@ abstract class Catalog extends database_object
$sql = "DELETE FROM `catalog` WHERE `catalog_type` = ?";
Dba::query($sql, array($this->get_type()));
- $sql = "DROP TABLE `catalog_" . $this->get_type() ."`";
+ $sql = "DROP TABLE `catalog_" . $this->get_type() . "`";
Dba::query($sql);
return true;
@@ -209,7 +209,7 @@ abstract class Catalog extends database_object
*/
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));
if ($results = Dba::fetch_assoc($db_results)) {
return self::create_catalog_type($results['catalog_type'], $id);
@@ -221,7 +221,7 @@ abstract class Catalog extends database_object
/**
* create_catalog_type
* This function attempts to create a catalog type
- * all Catalog modules should be located in /modules/catalog/.class.php
+ * all Catalog modules should be located in /modules/catalog//.class.php
* @param string $type
* @param int $id
* @return Catalog|null
@@ -232,8 +232,8 @@ abstract class Catalog extends database_object
return false;
}
- $filename = AmpConfig::get('prefix') . '/modules/catalog/' . $type . '.catalog.php';
- $include = require_once $filename;
+ $filename = AmpConfig::get('prefix') . '/modules/catalog/' . $type . '/' . $type . '.catalog.php';
+ $include = require_once $filename;
if (!$include) {
/* Throw Error Here */
@@ -265,14 +265,14 @@ abstract class Catalog extends database_object
"var type_fields = new Array();" .
"type_fields['none'] = '';";
$seltypes = '';
- $types = self::get_catalog_types();
+ $types = self::get_catalog_types();
foreach ($types as $type) {
$catalog = self::create_catalog_type($type);
if ($catalog->is_installed()) {
$seltypes .= '';
echo "type_fields['" . $type . "'] = \"";
$fields = $catalog->catalog_fields();
- $help = $catalog->get_create_help();
+ $help = $catalog->get_create_help();
if (!empty($help)) {
echo "
" . $help . "
";
}
@@ -313,7 +313,8 @@ abstract class Catalog extends database_object
public static function get_catalog_types()
{
/* First open the dir */
- $handle = opendir(AmpConfig::get('prefix') . '/modules/catalog');
+ $basedir = AmpConfig::get('prefix') . '/modules/catalog';
+ $handle = opendir($basedir);
if (!is_resource($handle)) {
debug_event('catalog', 'Error: Unable to read catalog types directory', '1');
@@ -323,16 +324,22 @@ abstract class Catalog extends database_object
$results = array();
while (false !== ($file = readdir($handle))) {
- if (substr($file, -11, 11) != 'catalog.php') {
+ if ($file === '.' || $file === '..') {
continue;
}
-
- /* Make sure it isn't a dir */
- if (!is_dir($file)) {
- /* Get the basename and then everything before catalog */
- $filename = basename($file, '.catalog.php');
- $results[] = $filename;
+ /* Make sure it is a dir */
+ if (! is_dir($basedir . '/' . $file)) {
+ debug_event('catalog', $file . ' is not a directory.', 3);
+ continue;
}
+
+ // Make sure the plugin base file exists inside the plugin directory
+ if (! file_exists($basedir . '/' . $file . '/' . $file . '.catalog.php')) {
+ debug_event('catalog', 'Missing class for ' . $file, 3);
+ continue;
+ }
+
+ $results[] = $file;
} // end while
return $results;
@@ -381,8 +388,8 @@ abstract class Catalog extends database_object
{
$info = parent::get_info($id, $table);
- $table = 'catalog_' . $this->get_type();
- $sql = "SELECT `id` FROM $table WHERE `catalog_id` = ?";
+ $table = 'catalog_' . $this->get_type();
+ $sql = "SELECT `id` FROM $table WHERE `catalog_id` = ?";
$db_results = Dba::read($sql, array($id));
if ($results = Dba::fetch_assoc($db_results)) {
@@ -430,7 +437,7 @@ abstract class Catalog extends database_object
{
if (count($this->_filecache) == 0) {
// Get _EVERYTHING_
- $sql = 'SELECT `id`, `file` FROM `song` WHERE `catalog` = ?';
+ $sql = 'SELECT `id`, `file` FROM `song` WHERE `catalog` = ?';
$db_results = Dba::read($sql, array($this->id));
// Populate the filecache
@@ -438,7 +445,7 @@ abstract class Catalog extends database_object
$this->_filecache[strtolower($results['file'])] = $results['id'];
}
- $sql = 'SELECT `id`,`file` FROM `video` WHERE `catalog` = ?';
+ $sql = 'SELECT `id`,`file` FROM `video` WHERE `catalog` = ?';
$db_results = Dba::read($sql, array($this->id));
while ($results = Dba::fetch_assoc($db_results)) {
@@ -498,7 +505,7 @@ abstract class Catalog extends database_object
public function format()
{
$this->f_name = $this->name;
- $this->link = AmpConfig::get('web_path') . '/admin/catalog.php?action=show_customize_catalog&catalog_id=' . $this->id;
+ $this->link = AmpConfig::get('web_path') . '/admin/catalog.php?action=show_customize_catalog&catalog_id=' . $this->id;
$this->f_link = '' .
scrub_out($this->f_name) . '';
$this->f_update = $this->last_update
@@ -519,10 +526,16 @@ abstract class Catalog extends database_object
* of what you find
* @return int[]
*/
- public static function get_catalogs()
+ public static function get_catalogs($filter_type='')
{
- $sql = "SELECT `id` FROM `catalog` ORDER BY `name`";
- $db_results = Dba::read($sql);
+ $params = array();
+ $sql = "SELECT `id` FROM `catalog` ";
+ if (!empty($filter_type)) {
+ $sql .= "WHERE `gather_types` = ? ";
+ $params[] = $filter_type;
+ }
+ $sql .= "ORDER BY `name`";
+ $db_results = Dba::read($sql, $params);
$results = array();
@@ -571,15 +584,15 @@ abstract class Catalog extends database_object
*/
public static function get_stats($catalog_id = null)
{
- $results = self::count_medias($catalog_id);
- $results = array_merge(User::count(), $results);
+ $results = self::count_medias($catalog_id);
+ $results = array_merge(User::count(), $results);
$results['tags'] = self::count_tags();
$hours = floor($results['time'] / 3600);
$results['formatted_size'] = UI::format_bytes($results['size']);
- $days = floor($hours / 24);
+ $days = floor($hours / 24);
$hours = $hours % 24;
$time_text = "$days ";
@@ -601,20 +614,20 @@ abstract class Catalog extends database_object
*/
public static function create($data)
{
- $name = $data['name'];
- $type = $data['type'];
+ $name = $data['name'];
+ $type = $data['type'];
$rename_pattern = $data['rename_pattern'];
- $sort_pattern = $data['sort_pattern'];
- $gather_types = $data['gather_media'];
+ $sort_pattern = $data['sort_pattern'];
+ $gather_types = $data['gather_media'];
// Should it be an array? Not now.
- if (!in_array($gather_types, array('music', 'clip', 'tvshow', 'movie', 'personal_video'))) {
+ if (!in_array($gather_types, array('music', 'clip', 'tvshow', 'movie', 'personal_video', 'podcast'))) {
return 0;
}
$insert_id = 0;
- $filename = AmpConfig::get('prefix') . '/modules/catalog/' . $type . '.catalog.php';
- $include = require_once $filename;
+ $filename = AmpConfig::get('prefix') . '/modules/catalog/' . $type . '/' . $type . '.catalog.php';
+ $include = require_once $filename;
if ($include) {
$sql = 'INSERT INTO `catalog` (`name`, `catalog_type`, ' .
@@ -630,7 +643,7 @@ abstract class Catalog extends database_object
$insert_id = Dba::insert_id();
if (!$insert_id) {
- Error::add('general', T_('Catalog Insert Failed check debug logs'));
+ AmpError::add('general', T_('Catalog Insert Failed check debug logs'));
debug_event('catalog', 'Insert failed: ' . json_encode($data), 2);
return 0;
}
@@ -655,7 +668,7 @@ abstract class Catalog extends database_object
public static function count_tags()
{
// FIXME: Ignores catalog_id
- $sql = "SELECT COUNT(`id`) FROM `tag`";
+ $sql = "SELECT COUNT(`id`) FROM `tag`";
$db_results = Dba::read($sql);
$row = Dba::fetch_row($db_results);
@@ -673,53 +686,64 @@ abstract class Catalog extends database_object
public static function count_medias($catalog_id = null)
{
$where_sql = $catalog_id ? 'WHERE `catalog` = ?' : '';
- $params = $catalog_id ? array($catalog_id) : null;
+ $params = $catalog_id ? array($catalog_id) : null;
$sql = 'SELECT COUNT(`id`), SUM(`time`), SUM(`size`) FROM `song` ' .
$where_sql;
$db_results = Dba::read($sql, $params);
- $data = Dba::fetch_row($db_results);
- $songs = $data[0];
- $time = $data[1];
- $size = $data[2];
+ $data = Dba::fetch_row($db_results);
+ $songs = $data[0];
+ $time = $data[1];
+ $size = $data[2];
$sql = 'SELECT COUNT(`id`), SUM(`time`), SUM(`size`) FROM `video` ' .
$where_sql;
$db_results = Dba::read($sql, $params);
- $data = Dba::fetch_row($db_results);
- $videos = $data[0];
+ $data = Dba::fetch_row($db_results);
+ $videos = $data[0];
$time += $data[1];
$size += $data[2];
- $sql = 'SELECT COUNT(DISTINCT(`album`)) FROM `song` ' . $where_sql;
+ $sql = 'SELECT COUNT(DISTINCT(`album`)) FROM `song` ' . $where_sql;
$db_results = Dba::read($sql, $params);
- $data = Dba::fetch_row($db_results);
- $albums = $data[0];
+ $data = Dba::fetch_row($db_results);
+ $albums = $data[0];
- $sql = 'SELECT COUNT(DISTINCT(`artist`)) FROM `song` ' . $where_sql;
+ $sql = 'SELECT COUNT(DISTINCT(`artist`)) FROM `song` ' . $where_sql;
$db_results = Dba::read($sql, $params);
- $data = Dba::fetch_row($db_results);
- $artists = $data[0];
+ $data = Dba::fetch_row($db_results);
+ $artists = $data[0];
- $sql = 'SELECT COUNT(`id`) FROM `search`';
- $db_results = Dba::read($sql, $params);
- $data = Dba::fetch_row($db_results);
+ $sql = 'SELECT COUNT(`id`) FROM `search`';
+ $db_results = Dba::read($sql, $params);
+ $data = Dba::fetch_row($db_results);
$smartplaylists = $data[0];
- $sql = 'SELECT COUNT(`id`) FROM `playlist`';
+ $sql = 'SELECT COUNT(`id`) FROM `playlist`';
$db_results = Dba::read($sql, $params);
- $data = Dba::fetch_row($db_results);
- $playlists = $data[0];
+ $data = Dba::fetch_row($db_results);
+ $playlists = $data[0];
+
+ $sql = 'SELECT COUNT(`id`) FROM `live_stream`';
+ $db_results = Dba::read($sql, $params);
+ $data = Dba::fetch_row($db_results);
+ $live_streams = $data[0];
+
+ $sql = 'SELECT COUNT(`id`) FROM `podcast`';
+ $db_results = Dba::read($sql, $params);
+ $data = Dba::fetch_row($db_results);
+ $podcasts = $data[0];
- $results = array();
- $results['songs'] = $songs;
- $results['videos'] = $videos;
- $results['albums'] = $albums;
- $results['artists'] = $artists;
- $results['playlists'] = $playlists;
+ $results = array();
+ $results['songs'] = $songs;
+ $results['videos'] = $videos;
+ $results['albums'] = $albums;
+ $results['artists'] = $artists;
+ $results['playlists'] = $playlists;
$results['smartplaylists'] = $smartplaylists;
- $results['size'] = $size;
- $results['time'] = $time;
+ $results['podcasts'] = $podcasts;
+ $results['size'] = $size;
+ $results['time'] = $time;
return $results;
}
@@ -766,7 +790,7 @@ abstract class Catalog extends database_object
{
$results = array();
- $sql = 'SELECT DISTINCT(`song`.`album`) FROM `song` WHERE `song`.`catalog` = ?';
+ $sql = 'SELECT DISTINCT(`song`.`album`) FROM `song` WHERE `song`.`catalog` = ?';
$db_results = Dba::read($sql, array($this->id));
while ($r = Dba::fetch_assoc($db_results)) {
@@ -815,7 +839,7 @@ abstract class Catalog extends database_object
$results = array();
foreach ($catalogs as $catalog_id) {
- $catalog = Catalog::create_from_id($catalog_id);
+ $catalog = Catalog::create_from_id($catalog_id);
$video_ids = $catalog->get_video_ids($type);
foreach ($video_ids as $video_id) {
$results[] = Video::create_from_id($video_id);
@@ -841,7 +865,7 @@ abstract class Catalog extends database_object
$sql .= "WHERE `video`.`catalog` = `" . intval($catalog_id) . "`";
}
$db_results = Dba::read($sql);
- $video_cnt = 0;
+ $video_cnt = 0;
if ($row = Dba::fetch_row($db_results)) {
$video_cnt = $row[0];
}
@@ -886,7 +910,7 @@ abstract class Catalog extends database_object
$results = array();
foreach ($catalogs as $catalog_id) {
- $catalog = Catalog::create_from_id($catalog_id);
+ $catalog = Catalog::create_from_id($catalog_id);
$tvshow_ids = $catalog->get_tvshow_ids();
foreach ($tvshow_ids as $tvshow_id) {
$results[] = new TVShow($tvshow_id);
@@ -907,7 +931,7 @@ abstract class Catalog extends database_object
{
$results = array();
- $sql = 'SELECT DISTINCT(`song`.`artist`) FROM `song` WHERE `song`.`catalog` = ?';
+ $sql = 'SELECT DISTINCT(`song`.`artist`) FROM `song` WHERE `song`.`catalog` = ?';
$db_results = Dba::read($sql, array($this->id));
while ($r = Dba::fetch_assoc($db_results)) {
@@ -928,8 +952,8 @@ abstract class Catalog extends database_object
{
$sql_where = "";
if (is_array($catalogs) && count($catalogs)) {
- $catlist = '(' . implode(',', $catalogs) . ')';
- $sql_where = "WHERE `song`.`catalog` IN $catlist";
+ $catlist = '(' . implode(',', $catalogs) . ')';
+ $sql_where = "WHERE `song`.`catalog` IN $catlist ";
}
$sql_limit = "";
@@ -943,12 +967,13 @@ abstract class Catalog extends database_object
$sql_limit = "LIMIT " . $offset . ", 18446744073709551615";
}
- $sql = "SELECT `artist`.id, `artist`.`name`, `artist`.`summary` FROM `song` LEFT JOIN `artist` ON `artist`.`id` = `song`.`artist` " .
+ $sql = "SELECT `artist`.`id`, `artist`.`name`, `artist`.`summary`, (SELECT COUNT(DISTINCT album) from `song` as `inner_song` WHERE `inner_song`.`artist` = `song`.`artist`) AS `albums`" .
+ "FROM `song` LEFT JOIN `artist` ON `artist`.`id` = `song`.`artist` " .
$sql_where .
- "GROUP BY `song`.artist ORDER BY `artist`.`name` " .
+ "GROUP BY `artist`.`id`, `artist`.`name`, `artist`.`summary`, `song`.`artist` ORDER BY `artist`.`name` " .
$sql_limit;
- $results = array();
+ $results = array();
$db_results = Dba::read($sql);
while ($r = Dba::fetch_assoc($db_results)) {
@@ -960,15 +985,15 @@ abstract class Catalog extends database_object
public static function search_childrens($name, $catalog_id = 0)
{
- $search = array();
- $search['type'] = "artist";
- $search['rule_0_input'] = $name;
+ $search = array();
+ $search['type'] = "artist";
+ $search['rule_0_input'] = $name;
$search['rule_0_operator'] = 4;
- $search['rule_0'] = "name";
+ $search['rule_0'] = "name";
if ($catalog_id > 0) {
- $search['rule_1_input'] = $catalog_id;
+ $search['rule_1_input'] = $catalog_id;
$search['rule_1_operator'] = 0;
- $search['rule_1'] = "catalog";
+ $search['rule_1'] = "catalog";
}
$artists = Search::run($search);
@@ -995,7 +1020,7 @@ abstract class Catalog extends database_object
{
$sql_where = "";
if (is_array($catalogs) && count($catalogs)) {
- $catlist = '(' . implode(',', $catalogs) . ')';
+ $catlist = '(' . implode(',', $catalogs) . ')';
$sql_where = "WHERE `song`.`catalog` IN $catlist";
}
@@ -1010,10 +1035,10 @@ abstract class Catalog extends database_object
$sql_limit = "LIMIT $offset, 18446744073709551615";
}
- $sql = "SELECT `album`.`id` FROM `song` LEFT JOIN `album` ON `album`.`id` = `song`.`album` $sql_where GROUP BY `song`.`album` ORDER BY `album`.`name` $sql_limit";
+ $sql = "SELECT `album`.`id` FROM `song` LEFT JOIN `album` ON `album`.`id` = `song`.`album` $sql_where GROUP BY `album`.`id` ORDER BY `album`.`name` $sql_limit";
$db_results = Dba::read($sql);
- $results = array();
+ $results = array();
while ($r = Dba::fetch_assoc($db_results)) {
$results[] = $r['id'];
}
@@ -1034,7 +1059,7 @@ abstract class Catalog extends database_object
{
$sql_where = "";
if (is_array($catalogs) && count($catalogs)) {
- $catlist = '(' . implode(',', $catalogs) . ')';
+ $catlist = '(' . implode(',', $catalogs) . ')';
$sql_where = "WHERE `song`.`catalog` IN $catlist";
}
@@ -1049,17 +1074,105 @@ abstract class Catalog extends database_object
$sql_limit = "LIMIT $offset, 18446744073709551615";
}
- $sql = "SELECT `album`.`id` FROM `song` LEFT JOIN `album` ON `album`.`id` = `song`.`album` " .
+ $sql = "SELECT `song`.`album` FROM `song` LEFT JOIN `album` ON `album`.`id` = `song`.`album` " .
"LEFT JOIN `artist` ON `artist`.`id` = `song`.`artist` $sql_where GROUP BY `song`.`album` ORDER BY `artist`.`name`, `artist`.`id`, `album`.`name` $sql_limit";
$db_results = Dba::read($sql);
- $results = array();
+ $results = array();
while ($r = Dba::fetch_assoc($db_results)) {
$results[] = $r['id'];
}
return $results;
}
+
+ /**
+ * get_podcast_ids
+ *
+ * This returns an array of ids of podcasts in this catalog
+ * @return int[]
+ */
+ public function get_podcast_ids()
+ {
+ $results = array();
+
+ $sql = 'SELECT `podcast`.`id` FROM `podcast` ';
+ $sql .= 'WHERE `podcast`.`catalog` = ?';
+ $db_results = Dba::read($sql, array($this->id));
+ while ($r = Dba::fetch_assoc($db_results)) {
+ $results[] = $r['id'];
+ }
+
+ return $results;
+ }
+
+ /**
+ *
+ * @param int[]|null $catalogs
+ * @return \Podcast[]
+ */
+ public static function get_podcasts($catalogs = null)
+ {
+ if (!$catalogs) {
+ $catalogs = self::get_catalogs();
+ }
+
+ $results = array();
+ foreach ($catalogs as $catalog_id) {
+ $catalog = Catalog::create_from_id($catalog_id);
+ $podcast_ids = $catalog->get_podcast_ids();
+ foreach ($podcast_ids as $podcast_id) {
+ $results[] = new Podcast($podcast_id);
+ }
+ }
+
+ return $results;
+ }
+
+ /**
+ * get_newest_podcasts_ids
+ *
+ * This returns an array of ids of latest podcast episodes in this catalog
+ * @return int[]
+ */
+ public function get_newest_podcasts_ids()
+ {
+ $results = array();
+
+ $sql = 'SELECT `podcast_episode`.`id` FROM `podcast_episode` ' .
+ 'INNER JOIN `podcast` ON `podcast`.`id` = `podcast_episode`.`podcast` ' .
+ 'WHERE `podcast`.`catalog` = ? ' .
+ 'ORDER BY `podcast_episode`.`pubdate` DESC';
+ $db_results = Dba::read($sql, array($this->id));
+ while ($r = Dba::fetch_assoc($db_results)) {
+ $results[] = $r['id'];
+ }
+
+ return $results;
+ }
+
+ /**
+ *
+ * @param int[]|null $catalogs
+ * @return \Podcast_Episode[]
+ */
+ public static function get_newest_podcasts($catalogs = null)
+ {
+ if (!$catalogs) {
+ $catalogs = self::get_catalogs();
+ }
+
+ $results = array();
+ foreach ($catalogs as $catalog_id) {
+ $catalog = Catalog::create_from_id($catalog_id);
+ $episode_ids = $catalog->get_newest_podcasts_ids();
+ foreach ($episode_ids as $episode_id) {
+ $results[] = new Podcast_Episode($episode_id);
+ }
+ }
+
+ return $results;
+ }
/**
*
@@ -1083,7 +1196,7 @@ abstract class Catalog extends database_object
// Only search on items with default art kind as `default`.
if ($libitem->get_default_art_kind() == 'default') {
$keywords = $libitem->get_keywords();
- $keyword = '';
+ $keyword = '';
foreach ($keywords as $key => $word) {
$options[$key] = $word['value'];
if ($word['important']) {
@@ -1104,7 +1217,7 @@ abstract class Catalog extends database_object
}
}
- $art = new Art($id, $type);
+ $art = new Art($id, $type);
$results = $art->gather($options, 1);
if (count($results)) {
@@ -1114,7 +1227,7 @@ abstract class Catalog extends database_object
$art->insert($image, $results[0]['mime']);
// If they've enabled resizing of images generate a thumbnail
if (AmpConfig::get('resize_images')) {
- $size = array('width' => 275, 'height' => 275);
+ $size = array('width' => 275, 'height' => 275);
$thumb = $art->generate_thumb($image,$size ,$results[0]['mime']);
if (is_array($thumb)) {
$art->save_thumb($thumb['thumb'], $thumb['thumb_mime'], $size);
@@ -1156,12 +1269,12 @@ abstract class Catalog extends database_object
set_time_limit(0);
$search_count = 0;
- $searches = array();
+ $searches = array();
if ($songs == null) {
- $searches['album'] = $this->get_album_ids();
+ $searches['album'] = $this->get_album_ids();
$searches['artist'] = $this->get_artist_ids();
} else {
- $searches['album'] = array();
+ $searches['album'] = array();
$searches['artist'] = array();
foreach ($songs as $song_id) {
$song = new Song($song_id);
@@ -1206,10 +1319,10 @@ abstract class Catalog extends database_object
*/
public function get_songs()
{
- $songs = array();
+ $songs = array();
$results = array();
- $sql = "SELECT `id` FROM `song` WHERE `catalog` = ? AND `enabled`='1'";
+ $sql = "SELECT `id` FROM `song` WHERE `catalog` = ? AND `enabled`='1'";
$db_results = Dba::read($sql, array($this->id));
while ($row = Dba::fetch_assoc($db_results)) {
@@ -1245,7 +1358,7 @@ abstract class Catalog extends database_object
// Run through them and get the art!
foreach ($albums as $album_id) {
$album = new Album($album_id);
- $art = new Art($album_id, 'album');
+ $art = new Art($album_id, 'album');
if (!$art->get_db()) {
continue;
@@ -1253,8 +1366,8 @@ abstract class Catalog extends database_object
// Get the first song in the album
$songs = $album->get_songs(1);
- $song = new Song($songs[0]);
- $dir = dirname($song->file);
+ $song = new Song($songs[0]);
+ $dir = dirname($song->file);
$extension = Art::extension($art->raw_mime);
@@ -1274,12 +1387,12 @@ abstract class Catalog extends database_object
switch ($methods['metadata']) {
case 'windows':
$meta_file = $dir . '/desktop.ini';
- $string = "[.ShellClassInfo]\nIconFile=$file\nIconIndex=0\nInfoTip=$album->full_name";
+ $string = "[.ShellClassInfo]\nIconFile=$file\nIconIndex=0\nInfoTip=$album->full_name";
break;
case 'linux':
default:
$meta_file = $dir . '/.directory';
- $string = "Name=$album->full_name\nIcon=$file";
+ $string = "Name=$album->full_name\nIcon=$file";
break;
}
@@ -1310,7 +1423,7 @@ abstract class Catalog extends database_object
protected function update_last_update()
{
$date = time();
- $sql = "UPDATE `catalog` SET `last_update` = ? WHERE `id` = ?";
+ $sql = "UPDATE `catalog` SET `last_update` = ? WHERE `id` = ?";
Dba::write($sql, array($date, $this->id));
} // update_last_update
@@ -1321,7 +1434,7 @@ abstract class Catalog extends database_object
public function update_last_add()
{
$date = time();
- $sql = "UPDATE `catalog` SET `last_add` = ? WHERE `id` = ?";
+ $sql = "UPDATE `catalog` SET `last_add` = ? WHERE `id` = ?";
Dba::write($sql, array($date, $this->id));
} // update_last_add
@@ -1332,7 +1445,7 @@ abstract class Catalog extends database_object
public function update_last_clean()
{
$date = time();
- $sql = "UPDATE `catalog` SET `last_clean` = ? WHERE `id` = ?";
+ $sql = "UPDATE `catalog` SET `last_clean` = ? WHERE `id` = ?";
Dba::write($sql, array($date, $this->id));
} // update_last_clean
@@ -1344,7 +1457,7 @@ abstract class Catalog extends database_object
*/
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']);
Dba::write($sql, $params);
@@ -1372,7 +1485,7 @@ abstract class Catalog extends database_object
break;
case 'artist':
$artist = new Artist($id);
- $songs = $artist->get_songs();
+ $songs = $artist->get_songs();
break;
case 'song':
$songs[] = $id;
@@ -1381,7 +1494,7 @@ abstract class Catalog extends database_object
foreach ($songs as $song_id) {
$song = new Song($song_id);
- $info = self::update_media_from_tags($song, '', '');
+ $info = self::update_media_from_tags($song);
if ($info['change']) {
$file = scrub_out($song->file);
@@ -1411,18 +1524,18 @@ abstract class Catalog extends database_object
* @param string $rename_pattern
* @return array
*/
- public static function update_media_from_tags($media, $sort_pattern='', $rename_pattern='')
+ public static function update_media_from_tags($media, $gather_types = array('music'), $sort_pattern='', $rename_pattern='')
{
// Check for patterns
if (!$sort_pattern or !$rename_pattern) {
- $catalog = Catalog::create_from_id($media->catalog);
- $sort_pattern = $catalog->sort_pattern;
+ $catalog = Catalog::create_from_id($media->catalog);
+ $sort_pattern = $catalog->sort_pattern;
$rename_pattern = $catalog->rename_pattern;
}
debug_event('tag-read', 'Reading tags from ' . $media->file, 5);
- $vainfo = new vainfo($media->file, array('music'), '', '', '', $sort_pattern, $rename_pattern);
+ $vainfo = new vainfo($media->file, $gather_types, '', '', '', $sort_pattern, $rename_pattern);
$vainfo->get_info();
$key = vainfo::get_tag_type($vainfo->tags);
@@ -1464,21 +1577,21 @@ abstract class Catalog extends database_object
array("\r\n", "\r", "\n"),
' ',
strip_tags($results['lyrics']));
- $new_song->bitrate = $results['bitrate'];
- $new_song->rate = $results['rate'];
- $new_song->mode = ($results['mode'] == 'cbr') ? 'cbr' : 'vbr';
- $new_song->size = $results['size'];
- $new_song->time = $results['time'];
- $new_song->mime = $results['mime'];
- $new_song->track = intval($results['track']);
- $new_song->mbid = $results['mb_trackid'];
- $new_song->label = $results['publisher'];
- $new_song->composer = $results['composer'];
+ $new_song->bitrate = $results['bitrate'];
+ $new_song->rate = $results['rate'];
+ $new_song->mode = ($results['mode'] == 'cbr') ? 'cbr' : 'vbr';
+ $new_song->size = $results['size'];
+ $new_song->time = $results['time'];
+ $new_song->mime = $results['mime'];
+ $new_song->track = intval($results['track']);
+ $new_song->mbid = $results['mb_trackid'];
+ $new_song->label = $results['publisher'];
+ $new_song->composer = $results['composer'];
$new_song->replaygain_track_gain = floatval($results['replaygain_track_gain']);
$new_song->replaygain_track_peak = floatval($results['replaygain_track_peak']);
$new_song->replaygain_album_gain = floatval($results['replaygain_album_gain']);
$new_song->replaygain_album_peak = floatval($results['replaygain_album_peak']);
- $tags = Tag::get_object_tags('song', $song->id);
+ $tags = Tag::get_object_tags('song', $song->id);
if ($tags) {
foreach ($tags as $tag) {
$song->tags[] = $tag['name'];
@@ -1508,6 +1621,17 @@ abstract class Catalog extends database_object
/* Since we're doing a full compare make sure we fill the extended information */
$song->fill_ext_info();
+
+ if (Song::isCustomMetadataEnabled()) {
+ $ctags = self::get_clean_metadata($song, $results);
+ if (method_exists($song, 'updateOrInsertMetadata') && $song::isCustomMetadataEnabled()) {
+ $ctags = array_diff_key($ctags, array_flip($song->getDisabledMetadataFields()));
+ foreach ($ctags as $tag => $value) {
+ $field = $song->getField($tag);
+ $song->updateOrInsertMetadata($field, $value);
+ }
+ }
+ }
$info = Song::compare_song_information($song, $new_song);
if ($info['change']) {
@@ -1543,13 +1667,92 @@ abstract class Catalog extends database_object
debug_event('update', "$song->file : no differences found", 5);
}
+ // If song rating tag exists and is well formed (array user=>rating), update it
+ if ($song->id && array_key_exists('rating', $results) && is_array($results['rating'])) {
+ // For each user's ratings, call the function
+ foreach ($results['rating'] as $user => $rating) {
+ debug_event('Rating', "Updating rating for Song " . $song->id . " to $rating for user $user", 5);
+ $o_rating = new Rating($song->id, 'song');
+ $o_rating->set_rating($rating, $user);
+ }
+ }
return $info;
} // update_song_from_tags
- public function update_video_from_tags($results, Video $video)
+ public static function update_video_from_tags($results, Video $video)
{
- // TODO: implement this
- return null;
+ /* Setup the vars */
+ $new_video = new Video();
+ $new_video->file = $results['file'];
+ $new_video->title = $results['title'];
+ $new_video->size = $results['size'];
+ $new_video->video_codec = $results['video_codec'];
+ $new_video->audio_codec = $results['audio_codec'];
+ $new_video->resolution_x = $results['resolution_x'];
+ $new_video->resolution_y = $results['resolution_y'];
+ $new_video->time = $results['time'];
+ $new_video->release_date = $results['release_date'] ?: 0;
+ $new_video->bitrate = $results['bitrate'];
+ $new_video->mode = $results['mode'];
+ $new_video->channels = $results['channels'];
+ $new_video->display_x = $results['display_x'];
+ $new_video->display_y = $results['display_y'];
+ $new_video->frame_rate = $results['frame_rate'];
+ $new_video->video_bitrate = $results['video_bitrate'];
+ $tags = Tag::get_object_tags('video', $video->id);
+ if ($tags) {
+ foreach ($tags as $tag) {
+ $video->tags[] = $tag['name'];
+ }
+ }
+ $new_video->tags = $results['genre'];
+
+ $info = Video::compare_video_information($video, $new_video);
+ if ($info['change']) {
+ debug_event('update', $video->file . " : differences found, updating database", 5);
+
+ $video->update_video($video->id, $new_video);
+
+ if ($video->tags != $new_video->tags) {
+ Tag::update_tag_list(implode(',', $new_video->tags), 'video', $video->id, true);
+ }
+ } else {
+ debug_event('update', $video->file . " : no differences found", 5);
+ }
+
+ return $info;
+ }
+
+ /**
+ * Get rid of all tags found in the libraryItem
+ * @param library_item $libraryItem
+ * @param array $metadata
+ * @return array
+ */
+ private static function get_clean_metadata(library_item $libraryItem, $metadata)
+ {
+ $tags = array_diff_key(
+ $metadata,
+ get_object_vars($libraryItem),
+ array_flip($libraryItem::$aliases ?: array())
+ );
+
+ return array_filter($tags);
+ }
+
+ /**
+ *
+ * @param library_item $libraryItem
+ * @param type $metadata
+ */
+ public static function add_metadata(library_item $libraryItem, $metadata)
+ {
+ $tags = self::get_clean_metadata($libraryItem, $metadata);
+
+ foreach ($tags as $tag => $value) {
+ $field = $libraryItem->getField($tag);
+ $libraryItem->addMetadata($field, $value);
+ }
}
/**
@@ -1589,14 +1792,14 @@ abstract class Catalog extends database_object
debug_event('clean', 'Starting on ' . $this->name, 5);
if (!defined('SSE_OUTPUT')) {
- require AmpConfig::get('prefix') . '/templates/show_clean_catalog.inc.php';
+ require AmpConfig::get('prefix') . UI::find_template('show_clean_catalog.inc.php');
ob_flush();
flush();
}
$dead_total = $this->clean_catalog_proc();
- debug_event('clean', 'clean finished, ' . $dead_total . ' removed from '. $this->name, 5);
+ debug_event('clean', 'clean finished, ' . $dead_total . ' removed from ' . $this->name, 5);
// Remove any orphaned artists/albums/etc.
self::gc();
@@ -1619,7 +1822,7 @@ abstract class Catalog extends database_object
public function verify_catalog()
{
if (!defined('SSE_OUTPUT')) {
- require AmpConfig::get('prefix') . '/templates/show_verify_catalog.inc.php';
+ require AmpConfig::get('prefix') . UI::find_template('show_verify_catalog.inc.php');
ob_flush();
flush();
}
@@ -1654,10 +1857,15 @@ abstract class Catalog extends database_object
Stats::gc();
Rating::gc();
Userflag::gc();
+ Useractivity::gc();
Playlist::gc();
Tmp_Playlist::gc();
Shoutbox::gc();
Tag::gc();
+
+ // TODO: use InnoDB with foreign keys and on delete cascade to get rid of garbage collection
+ \Lib\Metadata\Repository\Metadata::gc();
+ \Lib\Metadata\Repository\MetadataField::gc();
debug_event('catalog', 'Database cleanup ended', 5);
}
@@ -1682,6 +1890,32 @@ abstract class Catalog extends database_object
return array('string' => $string, 'prefix' => $prefix);
} // trim_prefix
+ public static function normalize_year($year)
+ {
+ if (empty($year)) {
+ return 0;
+ }
+
+ $year = intval($year);
+ if ($year < 0 || $year > 9999) {
+ return 0;
+ }
+
+ return $year;
+ }
+
+ /**
+ * trim_featuring
+ * Splits artists featuring from the string
+ * @param string $string
+ * @return array
+ */
+ public static function trim_featuring($string)
+ {
+ $trimmed = array_map('trim', explode(' feat. ', $string));
+ return $trimmed;
+ } // trim_featuring
+
/**
* check_title
* this checks to make sure something is
@@ -1708,7 +1942,7 @@ abstract class Catalog extends database_object
public static function import_playlist($playlist)
{
$data = file_get_contents($playlist);
- if (substr($playlist, -3, 3) == 'm3u') {
+ if (substr($playlist, -3, 3) == 'm3u' || substr($playlist, -4, 4) == 'm3u8') {
$files = self::parse_m3u($data);
} elseif (substr($playlist, -3, 3) == 'pls') {
$files = self::parse_pls($data);
@@ -1725,8 +1959,8 @@ abstract class Catalog extends database_object
$file = trim($file);
// Check to see if it's a url from this ampache instance
if (substr($file, 0, strlen(AmpConfig::get('web_path'))) == AmpConfig::get('web_path')) {
- $data = Stream_URL::parse($file);
- $sql = 'SELECT COUNT(*) FROM `song` WHERE `id` = ?';
+ $data = Stream_URL::parse($file);
+ $sql = 'SELECT COUNT(*) FROM `song` WHERE `id` = ?';
$db_results = Dba::read($sql, array($data['id']));
if (Dba::num_rows($db_results)) {
$songs[] = $data['id'];
@@ -1748,9 +1982,9 @@ abstract class Catalog extends database_object
debug_event('catalog', 'Add file ' . $file . ' to playlist.', '5');
// First, try to found the file as absolute path
- $sql = "SELECT `id` FROM `song` WHERE `file` = ?";
+ $sql = "SELECT `id` FROM `song` WHERE `file` = ?";
$db_results = Dba::read($sql, array($file));
- $results = Dba::fetch_assoc($db_results);
+ $results = Dba::fetch_assoc($db_results);
if (isset($results['id'])) {
$songs[] = $results['id'];
@@ -1760,9 +1994,9 @@ abstract class Catalog extends database_object
// Normalize the file path. realpath requires the files to exists.
$file = realpath($file);
if ($file) {
- $sql = "SELECT `id` FROM `song` WHERE `file` = ?";
+ $sql = "SELECT `id` FROM `song` WHERE `file` = ?";
$db_results = Dba::read($sql, array($file));
- $results = Dba::fetch_assoc($db_results);
+ $results = Dba::fetch_assoc($db_results);
if (isset($results['id'])) {
$songs[] = $results['id'];
@@ -1776,7 +2010,7 @@ abstract class Catalog extends database_object
debug_event('import_playlist', "Parsed " . $playlist . ", found " . count($songs) . " songs", 5);
if (count($songs)) {
- $name = $pinfo['extension'] . " - " . $pinfo['filename'];
+ $name = $pinfo['extension'] . " - " . $pinfo['filename'];
$playlist_id = Playlist::create($name, 'public');
if (!$playlist_id) {
@@ -1811,7 +2045,7 @@ abstract class Catalog extends database_object
*/
public static function parse_m3u($data)
{
- $files = array();
+ $files = array();
$results = explode("\n", $data);
foreach ($results as $value) {
@@ -1832,7 +2066,7 @@ abstract class Catalog extends database_object
*/
public static function parse_pls($data)
{
- $files = array();
+ $files = array();
$results = explode("\n", $data);
foreach ($results as $value) {
@@ -1857,7 +2091,7 @@ abstract class Catalog extends database_object
public static function parse_asx($data)
{
$files = array();
- $xml = simplexml_load_string($data);
+ $xml = simplexml_load_string($data);
if ($xml) {
foreach ($xml->entry as $entry) {
@@ -1880,7 +2114,7 @@ abstract class Catalog extends database_object
public static function parse_xspf($data)
{
$files = array();
- $xml = simplexml_load_string($data);
+ $xml = simplexml_load_string($data);
if ($xml) {
foreach ($xml->trackList->track as $track) {
$file = trim($track->location);
@@ -1905,7 +2139,7 @@ abstract class Catalog extends database_object
set_time_limit(0);
// 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));
// Only if the previous one works do we go on
@@ -1913,7 +2147,7 @@ abstract class Catalog extends database_object
return false;
}
- $sql = "DELETE FROM `video` WHERE `catalog` = ?";
+ $sql = "DELETE FROM `video` WHERE `catalog` = ?";
$db_results = Dba::write($sql, array($catalog_id));
if (!$db_results) {
@@ -1922,10 +2156,11 @@ abstract class Catalog extends database_object
$catalog = self::create_from_id($catalog_id);
- if (!$catalog->id)
+ if (!$catalog->id) {
return false;
+ }
- $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));
if (!$db_results) {
@@ -1968,21 +2203,21 @@ abstract class Catalog extends database_object
$song = new Song($results['id']);
$song->format();
- $xml = array();
- $xml['key']= $results['id'];
- $xml['dict']['Track ID']= intval($results['id']);
- $xml['dict']['Name'] = $song->title;
- $xml['dict']['Artist'] = $song->f_artist_full;
- $xml['dict']['Album'] = $song->f_album_full;
- $xml['dict']['Total Time'] = intval($song->time) * 1000; // iTunes uses milliseconds
+ $xml = array();
+ $xml['key'] = $results['id'];
+ $xml['dict']['Track ID'] = intval($results['id']);
+ $xml['dict']['Name'] = $song->title;
+ $xml['dict']['Artist'] = $song->f_artist_full;
+ $xml['dict']['Album'] = $song->f_album_full;
+ $xml['dict']['Total Time'] = intval($song->time) * 1000; // iTunes uses milliseconds
$xml['dict']['Track Number'] = intval($song->track);
- $xml['dict']['Year'] = intval($song->year);
- $xml['dict']['Date Added'] = date("Y-m-d\TH:i:s\Z", $song->addition_time);
- $xml['dict']['Bit Rate'] = intval($song->bitrate/1000);
- $xml['dict']['Sample Rate'] = intval($song->rate);
- $xml['dict']['Play Count'] = intval($song->played);
- $xml['dict']['Track Type'] = "URL";
- $xml['dict']['Location'] = Song::play_url($song->id);
+ $xml['dict']['Year'] = intval($song->year);
+ $xml['dict']['Date Added'] = date("Y-m-d\TH:i:s\Z", $song->addition_time);
+ $xml['dict']['Bit Rate'] = intval($song->bitrate/1000);
+ $xml['dict']['Sample Rate'] = intval($song->rate);
+ $xml['dict']['Play Count'] = intval($song->played);
+ $xml['dict']['Track Type'] = "URL";
+ $xml['dict']['Location'] = Song::play_url($song->id);
echo xoutput_from_array($xml, true, 'itunes');
// flush output buffer
} // while result
@@ -1997,12 +2232,12 @@ abstract class Catalog extends database_object
echo '"' . $song->id . '","' .
$song->title . '","' .
$song->f_artist_full . '","' .
- $song->f_album_full .'","' .
+ $song->f_album_full . '","' .
$song->f_time . '","' .
$song->f_track . '","' .
- $song->year .'","' .
+ $song->year . '","' .
date("Y-m-d\TH:i:s\Z", $song->addition_time) . '","' .
- $song->f_bitrate .'","' .
+ $song->f_bitrate . '","' .
$song->played . '","' .
$song->file . "\n";
}
@@ -2039,12 +2274,12 @@ abstract class Catalog extends database_object
*/
protected static function getSongTags($type, $id)
{
- $tags = array();
- $db_results = Dba::read('SELECT tag.name FROM tag'
- . ' JOIN tag_map ON tag.id = tag_map.tag_id'
- . ' JOIN song ON tag_map.object_id = song.id'
- . ' WHERE song.' . $type . ' = ? AND tag_map.object_type = "song"'
- . ' GROUP BY tag.id', array($id));
+ $tags = array();
+ $db_results = Dba::read('SELECT `tag`.`name` FROM `tag`'
+ . ' JOIN `tag_map` ON `tag`.`id` = `tag_map`.`tag_id`'
+ . ' JOIN `song` ON `tag_map`.`object_id` = `song`.`id`'
+ . ' WHERE `song`.`' . $type . '` = ? AND `tag_map`.`object_type` = "song"'
+ . ' GROUP BY `tag`.`id`, `tag`.`name`', array($id));
while ($row = Dba::fetch_assoc($db_results)) {
$tags[] = $row['name'];
}
@@ -2057,14 +2292,125 @@ abstract class Catalog extends database_object
$user = $GLOBALS['user']->id;
}
- if (!$user)
+ if (!$user) {
return false;
+ }
- if (!AmpConfig::get('delete_from_disk'))
+ if (!AmpConfig::get('delete_from_disk')) {
return false;
+ }
return (Access::check('interface','75') || ($libitem->get_user_owner() == $user && AmpConfig::get('upload_allow_remove')));
}
+
+ public static function process_action($action, $catalogs, $options = null)
+ {
+ if (!$options || !is_array($options)) {
+ $options = array();
+ }
+
+ switch ($action) {
+ case 'add_to_all_catalogs':
+ $catalogs = Catalog::get_catalogs();
+ case 'add_to_catalog':
+ if ($catalogs) {
+ foreach ($catalogs as $catalog_id) {
+ $catalog = Catalog::create_from_id($catalog_id);
+ if ($catalog !== null) {
+ $catalog->add_to_catalog($options);
+ }
+ }
+
+ if (!defined('SSE_OUTPUT')) {
+ AmpError::display('catalog_add');
+ }
+ }
+ break;
+ case 'update_all_catalogs':
+ $catalogs = Catalog::get_catalogs();
+ case 'update_catalog':
+ if ($catalogs) {
+ foreach ($catalogs as $catalog_id) {
+ $catalog = Catalog::create_from_id($catalog_id);
+ if ($catalog !== null) {
+ $catalog->verify_catalog();
+ }
+ }
+ }
+ break;
+ case 'full_service':
+ if (!$catalogs) {
+ $catalogs = Catalog::get_catalogs();
+ }
+
+ /* This runs the clean/verify/add in that order */
+ foreach ($catalogs as $catalog_id) {
+ $catalog = Catalog::create_from_id($catalog_id);
+ if ($catalog !== null) {
+ $catalog->clean_catalog();
+ $catalog->verify_catalog();
+ $catalog->add_to_catalog();
+ }
+ }
+ Dba::optimize_tables();
+ break;
+ case 'clean_all_catalogs':
+ $catalogs = Catalog::get_catalogs();
+ case 'clean_catalog':
+ if ($catalogs) {
+ foreach ($catalogs as $catalog_id) {
+ $catalog = Catalog::create_from_id($catalog_id);
+ if ($catalog !== null) {
+ $catalog->clean_catalog();
+ }
+ } // end foreach catalogs
+ Dba::optimize_tables();
+ }
+ break;
+ case 'update_from':
+ $catalog_id = 0;
+ // First see if we need to do an add
+ if ($options['add_path'] != '/' && strlen($options['add_path'])) {
+ if ($catalog_id = Catalog_local::get_from_path($options['add_path'])) {
+ $catalog = Catalog::create_from_id($catalog_id);
+ if ($catalog !== null) {
+ $catalog->add_to_catalog(array('subdirectory'=>$options['add_path']));
+ }
+ }
+ } // end if add
+
+ // Now check for an update
+ if ($options['update_path'] != '/' && strlen($options['update_path'])) {
+ if ($catalog_id = Catalog_local::get_from_path($options['update_path'])) {
+ $songs = Song::get_from_path($options['update_path']);
+ foreach ($songs as $song_id) {
+ Catalog::update_single_item('song',$song_id);
+ }
+ }
+ } // end if update
+
+ if ($catalog_id <= 0) {
+ AmpError::add('general', T_("This subdirectory is not part of an existing catalog. Update cannot be processed."));
+ }
+ break;
+ case 'gather_media_art':
+ if (!$catalogs) {
+ $catalogs = Catalog::get_catalogs();
+ }
+
+ // Iterate throught the catalogs and gather as needed
+ foreach ($catalogs as $catalog_id) {
+ $catalog = Catalog::create_from_id($catalog_id);
+ if ($catalog !== null) {
+ require AmpConfig::get('prefix') . UI::find_template('show_gather_art.inc.php');
+ flush();
+ $catalog->gather_art();
+ }
+ }
+ break;
+ }
+ }
}
// end of catalog class
+
diff --git a/sources/lib/class/channel.class.php b/sources/lib/class/channel.class.php
index c092f66..98a2a41 100644
--- a/sources/lib/class/channel.class.php
+++ b/sources/lib/class/channel.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -40,7 +40,7 @@ class Channel extends database_object implements media, library_item
public $description;
public $header_chunk;
- public $chunk_size = 4096;
+ public $chunk_size = 4096;
private $header_chunk_remainder = 0;
public $tags;
@@ -59,7 +59,9 @@ class Channel extends database_object implements media, library_item
*/
public function __construct($id=0)
{
- if (!$id) { return true; }
+ if (!$id) {
+ return true;
+ }
/* Get the information from the db */
$info = $this->get_info($id);
@@ -78,15 +80,15 @@ class Channel extends database_object implements media, library_item
Dba::write($sql, array($start_date, $address, $port, $pid, $this->id));
$this->start_date = $start_date;
- $this->interface = $address;
- $this->port = $port;
- $this->pid = $pid;
+ $this->interface = $address;
+ $this->port = $port;
+ $this->pid = $pid;
}
public function update_listeners($listeners, $addition=false)
{
- $sql = "UPDATE `channel` SET `listeners` = ? ";
- $params = array($listeners);
+ $sql = "UPDATE `channel` SET `listeners` = ? ";
+ $params = array($listeners);
$this->listeners = $listeners;
if ($listeners > $this->peak_listeners) {
$this->peak_listeners = $listeners;
@@ -103,7 +105,7 @@ class Channel extends database_object implements media, library_item
public function get_genre()
{
- $tags = Tag::get_object_tags('channel', $this->id);
+ $tags = Tag::get_object_tags('channel', $this->id);
$genre = "";
if ($tags) {
foreach ($tags as $tag) {
@@ -123,8 +125,8 @@ class Channel extends database_object implements media, library_item
public static function get_next_port()
{
- $port = 8200;
- $sql = "SELECT MAX(`port`) AS `max_port` FROM `channel`";
+ $port = 8200;
+ $sql = "SELECT MAX(`port`) AS `max_port` FROM `channel`";
$db_results = Dba::read($sql);
if ($results = Dba::fetch_assoc($db_results)) {
@@ -139,7 +141,7 @@ class Channel extends database_object implements media, library_item
public static function create($name, $description, $url, $object_type, $object_id, $interface, $port, $admin_password, $private, $max_listeners, $random, $loop, $stream_type, $bitrate)
{
if (!empty($name)) {
- $sql = "INSERT INTO `channel` (`name`, `description`, `url`, `object_type`, `object_id`, `interface`, `port`, `fixed_endpoint`, `admin_password`, `is_private`, `max_listeners`, `random`, `loop`, `stream_type`, `bitrate`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
+ $sql = "INSERT INTO `channel` (`name`, `description`, `url`, `object_type`, `object_id`, `interface`, `port`, `fixed_endpoint`, `admin_password`, `is_private`, `max_listeners`, `random`, `loop`, `stream_type`, `bitrate`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$params = array($name, $description, $url, $object_type, $object_id, $interface, $port, (!empty($interface) && !empty($port)), $admin_password, !empty($private), $max_listeners, $random, $loop, $stream_type, $bitrate);
return Dba::write($sql, $params);
}
@@ -182,7 +184,7 @@ class Channel extends database_object implements media, library_item
echo Ajax::button('?page=index&action=start_channel&id=' . $this->id,'run', T_('Start Channel'),'channel_start_' . $this->id);
echo " " . Ajax::button('?page=index&action=stop_channel&id=' . $this->id,'stop', T_('Stop Channel'),'channel_stop_' . $this->id);
echo " id . "\" onclick=\"showEditDialog('channel_row', '" . $this->id . "', 'edit_channel_" . $this->id . "', '" . T_('Channel edit') . "', 'channel_row_', 'refresh_channel')\">" . UI::get_icon('edit', T_('Edit')) . "";
- echo " id ."\">" . UI::get_icon('delete', T_('Delete')) . "";
+ echo " id . "\">" . UI::get_icon('delete', T_('Delete')) . "";
}
}
}
@@ -190,7 +192,7 @@ class Channel extends database_object implements media, library_item
public function format($details = true)
{
if ($details) {
- $this->tags = Tag::get_top_tags('channel', $this->id);
+ $this->tags = Tag::get_top_tags('channel', $this->id);
$this->f_tags = Tag::get_display($this->tags, true, 'channel');
}
}
@@ -284,9 +286,9 @@ class Channel extends database_object implements media, library_item
public static function get_channel_list()
{
- $sql = self::get_channel_list_sql();
+ $sql = self::get_channel_list_sql();
$db_results = Dba::read($sql);
- $results = array();
+ $results = array();
while ($row = Dba::fetch_assoc($db_results)) {
$results[] = $row['id'];
@@ -343,7 +345,7 @@ class Channel extends database_object implements media, library_item
protected function init_channel_songs()
{
$this->song_pos = 0;
- $this->songs = array();
+ $this->songs = array();
$this->playlist = $this->get_target_object();
if ($this->playlist) {
if (!$this->random) {
@@ -365,7 +367,7 @@ class Channel extends database_object implements media, library_item
// Move to next song
while ($this->media == null && ($this->random || $this->song_pos < count($this->songs))) {
if ($this->random) {
- $randsongs = $this->playlist->get_random_items(1);
+ $randsongs = $this->playlist->get_random_items(1);
$this->media = new Song($randsongs[0]['object_id']);
} else {
$this->media = new Song($this->songs[$this->song_pos]);
@@ -418,13 +420,14 @@ class Channel extends database_object implements media, library_item
$options = array(
'bitrate' => $this->bitrate
);
- $this->transcoder = Stream::start_transcode($this->media, $this->stream_type, null, $options);
+ $this->transcoder = Stream::start_transcode($this->media, $this->stream_type, null, $options);
$this->media_bytes_streamed = 0;
}
if (is_resource($this->transcoder['handle'])) {
- if (ftell($this->transcoder['handle']) == 0)
+ if (ftell($this->transcoder['handle']) == 0) {
$this->header_chunk = '';
+ }
$chunk = fread($this->transcoder['handle'], $this->chunk_size);
$this->media_bytes_streamed += strlen($chunk);
@@ -435,16 +438,16 @@ class Channel extends database_object implements media, library_item
if ($this->header_chunk_remainder) {
$this->header_chunk .= substr($clchunk, 0, $this->header_chunk_remainder);
if (strlen($clchunk) >= $this->header_chunk_remainder) {
- $clchunk = substr($clchunk, $this->header_chunk_remainder);
+ $clchunk = substr($clchunk, $this->header_chunk_remainder);
$this->header_chunk_remainder = 0;
} else {
$this->header_chunk_remainder = $this->header_chunk_remainder - strlen($clchunk);
- $clchunk = '';
+ $clchunk = '';
}
}
// see bin/channel_run.inc for explanation what's happening here
while ($this->strtohex(substr($clchunk, 0, 4)) == "4F676753") {
- $hex = $this->strtohex(substr($clchunk, 0, 27));
+ $hex = $this->strtohex(substr($clchunk, 0, 27));
$ogg_nr_of_segments = hexdec(substr($hex, 26*2, 2));
if ((substr($clchunk, 27 + $ogg_nr_of_segments + 1, 6) == "vorbis") || (substr($clchunk, 27 + $ogg_nr_of_segments, 4) == "Opus")) {
$hex .= $this->strtohex(substr($clchunk, 27, $ogg_nr_of_segments));
@@ -453,11 +456,13 @@ class Channel extends database_object implements media, library_item
$ogg_sum_segm_laces += hexdec(substr($hex, 27*2 + $segm*2, 2));
}
$this->header_chunk .= substr($clchunk, 0, 27 + $ogg_nr_of_segments + $ogg_sum_segm_laces);
- if (strlen($clchunk) < (27 + $ogg_nr_of_segments + $ogg_sum_segm_laces))
+ if (strlen($clchunk) < (27 + $ogg_nr_of_segments + $ogg_sum_segm_laces)) {
$this->header_chunk_remainder = (int) (27 + $ogg_nr_of_segments + $ogg_sum_segm_laces - strlen($clchunk));
+ }
$clchunk = substr($clchunk, 27 + $ogg_nr_of_segments + $ogg_sum_segm_laces);
- } else //no more interesting headers
+ } else { //no more interesting headers
$clchunk = '';
+ }
}
}
//debug_event('channel', 'File handle pointer: ' . ftell($this->transcoder['handle']) ,'5');
@@ -474,11 +479,11 @@ class Channel extends database_object implements media, library_item
fclose($this->transcoder['handle']);
Stream::kill_process($this->transcoder);
- $this->media = null;
+ $this->media = null;
$this->transcoder = null;
}
} else {
- $this->media = null;
+ $this->media = null;
$this->transcoder = null;
}
@@ -531,15 +536,15 @@ class Channel extends database_object implements media, library_item
public static function gc()
{
-
}
private function strtohex($x)
{
$s='';
- foreach(str_split($x) as $c) $s.=sprintf("%02X",ord($c));
+ foreach (str_split($x) as $c) {
+ $s.=sprintf("%02X",ord($c));
+ }
return($s);
}
-
-
} // end of channel class
+
diff --git a/sources/lib/class/clip.class.php b/sources/lib/class/clip.class.php
index 8975ca9..9b0aba5 100644
--- a/sources/lib/class/clip.class.php
+++ b/sources/lib/class/clip.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -44,7 +44,6 @@ class Clip extends Video
}
return true;
-
} // Constructor
/**
@@ -70,7 +69,6 @@ class Clip extends Video
Dba::write($sql, array($data['id'], $data['artist'], $data['song']));
return $data['id'];
-
} // create
/**
@@ -83,7 +81,6 @@ class Clip extends Video
Dba::write($sql, array($data['artist'], $data['song'], $this->id));
return $this->id;
-
} // update
/**
@@ -110,7 +107,6 @@ class Clip extends Video
}
return true;
-
} //format
/**
@@ -137,5 +133,5 @@ class Clip extends Video
return null;
}
-
} // Clip class
+
diff --git a/sources/lib/class/core.class.php b/sources/lib/class/core.class.php
index 636a3e8..2e28800 100644
--- a/sources/lib/class/core.class.php
+++ b/sources/lib/class/core.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -36,7 +36,6 @@ class Core
private function __construct()
{
return false;
-
} // construction
/**
@@ -48,41 +47,81 @@ class Core
*/
public static function autoload($class)
{
+ $possiblePaths = array();
if (strpos($class, '\\') === false) {
- $file = AmpConfig::get('prefix') . '/lib/class/' .
- strtolower($class) . '.class.php';
+ $possiblePaths = self::getNonNamespacedPaths($class);
+ } else {
+ $possiblePaths = self::getNamespacedPaths($class);
+ }
- if (Core::is_readable($file)) {
- require_once $file;
-
- // Call _auto_init if it exists
- $autocall = array($class, '_auto_init');
- if (is_callable($autocall)) {
- call_user_func($autocall);
- }
+ foreach ($possiblePaths as $path) {
+ if (is_file($path) && Core::is_readable($path)) {
+ require_once($path);
+ self::executeAutoCall($class);
} else {
debug_event('autoload', "'$class' not found!", 1);
}
- } else {
- // Class with namespace are not used by Ampache but probably by modules
- $split = explode('\\', $class);
- $path = AmpConfig::get('prefix') . '/modules';
- for ($i = 0; $i < count($split); ++$i) {
- $path .= '/' . $split[$i];
- if ($i != count($split)-1) {
- if (!is_dir($path)) {
- break;
- }
- } else {
- $path .= '.php';
- if (Core::is_readable($path)) {
- require_once $path;
- }
- }
- }
}
}
+ /**
+ * Execute _auto_init if availlable
+ * @param string $class
+ */
+ private static function executeAutoCall($class)
+ {
+ $autocall = array($class, '_auto_init');
+ if (is_callable($autocall)) {
+ call_user_func($autocall);
+ }
+ }
+
+ /**
+ * Place a new key on a specific position in array
+ * @param array $array
+ * @param integer $position
+ * @param array $add
+ * @return array
+ */
+ private static function insertInArray(array $array, $position, array $add)
+ {
+ return array_slice($array, 0, $position, true) +
+ $add +
+ array_slice($array, $position, null, true);
+ }
+
+ /**
+ * Get possible filepaths of namespaced classes
+ * @param string $class
+ * @return string
+ */
+ private static function getNamespacedPaths($class)
+ {
+ $possiblePaths = array();
+ $namespaceParts = explode('\\', $class);
+ $possiblePaths[] = AmpConfig::get('prefix') . '/modules/' . implode('/', $namespaceParts) . '.php';
+
+ $classedPath = array('path' => AmpConfig::get('prefix')) +
+ self::insertInArray($namespaceParts, 1, array('add' => 'class'));
+ $possiblePaths[] = implode('/', $classedPath) . '.php';
+
+ return $possiblePaths;
+ }
+
+ /**
+ * Get possible filepaths of non namespaced classes
+ * @param string $class
+ * @return string
+ */
+ private static function getNonNamespacedPaths($class)
+ {
+ $possiblePaths = array();
+ $possiblePaths[] = AmpConfig::get('prefix') . '/lib/class/' .
+ strtolower($class) . '.class.php';
+
+ return $possiblePaths;
+ }
+
/**
* form_register
* This registers a form with a SID, inserts it into the session
@@ -91,7 +130,7 @@ class Core
public static function form_register($name, $type = 'post')
{
// Make ourselves a nice little sid
- $sid = md5(uniqid(rand(), true));
+ $sid = md5(uniqid(rand(), true));
$window = AmpConfig::get('session_length');
$expire = time() + $window;
@@ -110,7 +149,6 @@ class Core
} // end switch on type
return $string;
-
} // form_register
/**
@@ -160,7 +198,6 @@ class Core
// OMG HAX0RZ
debug_event('Core', "$type form $sid failed consistency check, rejecting request", 2);
return false;
-
} // form_verify
/**
@@ -171,19 +208,24 @@ class Core
*/
public static function image_dimensions($image_data)
{
- if (!function_exists('ImageCreateFromString')) { return false; }
+ if (!function_exists('ImageCreateFromString')) {
+ return false;
+ }
$image = ImageCreateFromString($image_data);
- if (!$image) { return false; }
+ if (!$image) {
+ return false;
+ }
- $width = imagesx($image);
+ $width = imagesx($image);
$height = imagesy($image);
- if (!$width || !$height) { return false; }
+ if (!$width || !$height) {
+ return false;
+ }
return array('width'=>$width,'height'=>$height);
-
} // image_dimensions
/*
@@ -224,7 +266,7 @@ class Core
return false;
}
$offset = PHP_INT_MAX - 1;
- $size = (float) $offset;
+ $size = (float) $offset;
if (!fseek($fp, $offset)) {
return false;
}
@@ -246,9 +288,9 @@ class Core
*/
public static function conv_lc_file($filename)
{
- $lc_filename = $filename;
+ $lc_filename = $filename;
$site_charset = AmpConfig::get('site_charset');
- $lc_charset = AmpConfig::get('lc_charset');
+ $lc_charset = AmpConfig::get('lc_charset');
if ($lc_charset && $lc_charset != $site_charset) {
if (function_exists('iconv')) {
$lc_filename = iconv($site_charset, $lc_charset, $filename);
@@ -312,7 +354,7 @@ class Core
if (!isset($options['proxy'])) {
if (AmpConfig::get('proxy_host') && AmpConfig::get('proxy_port')) {
- $proxy = array();
+ $proxy = array();
$proxy[] = AmpConfig::get('proxy_host') . ':' . AmpConfig::get('proxy_port');
if (AmpConfig::get('proxy_user')) {
$proxy[] = AmpConfig::get('proxy_user');
@@ -326,3 +368,4 @@ class Core
return $options;
}
} // Core
+
diff --git a/sources/lib/class/daap_api.class.php b/sources/lib/class/daap_api.class.php
index 430626e..4428e8b 100644
--- a/sources/lib/class/daap_api.class.php
+++ b/sources/lib/class/daap_api.class.php
@@ -1,23 +1,23 @@
.
*
*/
@@ -26,11 +26,47 @@
*
* This class wrap Ampache to DAAP API functions. See https://github.com/andytinycat/daapdocs/blob/master/daapdocs.txt
* These are all static calls.
- *
*/
class Daap_Api
{
const AMPACHEID_SMARTPL = 400000000;
+ const BASE_LIBRARY = 0;
+
+ public static $metas = array(
+ 'dmap.itemid',
+ 'dmap.itemname',
+ 'dmap.itemkind',
+ 'dmap.persistentid',
+ 'daap.songalbum',
+ 'daap.songartist',
+ 'daap.songbitrate',
+ 'daap.songbeatsperminute',
+ 'daap.songcomment',
+ 'daap.songcompilation',
+ 'daap.songcomposer',
+ 'daap.songdateadded',
+ 'daap.songdatemodified',
+ 'daap.songdisccount',
+ 'daap.songdiscnumber',
+ 'daap.songdisabled',
+ 'daap.songeqpreset',
+ 'daap.songformat',
+ 'daap.songgenre',
+ 'daap.songdescription',
+ 'daap.songrelativevolume',
+ 'daap.songsamplerate',
+ 'daap.songsize',
+ 'daap.songstarttime',
+ 'daap.songstoptime',
+ 'daap.songtime',
+ 'daap.songtrackcount',
+ 'daap.songtracknumber',
+ 'daap.songuserrating',
+ 'daap.songyear',
+ 'daap.songdatakind',
+ 'daap.songdataurl',
+ 'com.apple.itunes.norm-volume'
+ );
public static $tags = array();
@@ -46,10 +82,10 @@ class Daap_Api
{
set_time_limit(0);
ob_end_clean();
-
+
if (function_exists('curl_version')) {
- $headers = apache_request_headers();
- $reqheaders = array();
+ $headers = apache_request_headers();
+ $reqheaders = array();
$reqheaders[] = "User-Agent: " . $headers['User-Agent'];
if (isset($headers['Range'])) {
$reqheaders[] = "Range: " . $headers['Range'];
@@ -61,8 +97,14 @@ class Daap_Api
CURLOPT_HEADER => false,
CURLOPT_RETURNTRANSFER => false,
CURLOPT_FOLLOWLOCATION => true,
- CURLOPT_WRITEFUNCTION => array('Daap_Api', 'output_body'),
- CURLOPT_HEADERFUNCTION => array('Daap_Api', 'output_header'),
+ CURLOPT_WRITEFUNCTION => array(
+ 'Daap_Api',
+ 'output_body'
+ ),
+ CURLOPT_HEADERFUNCTION => array(
+ 'Daap_Api',
+ 'output_header'
+ ),
// Ignore invalid certificate
// Default trusted chain is crap anyway and currently no custom CA option
CURLOPT_SSL_VERIFYPEER => false,
@@ -81,15 +123,15 @@ class Daap_Api
{
echo $data;
ob_flush();
-
+
return strlen($data);
}
public static function output_header($ch, $header)
{
$rheader = trim($header);
- $rhpart = explode(':', $rheader);
- if (!empty($rheader) && count($rhpart) > 1) {
+ $rhpart = explode(':', $rheader);
+ if (! empty($rheader) && count($rhpart) > 1) {
if ($rhpart[0] != "Transfer-Encoding") {
header($rheader);
}
@@ -99,7 +141,6 @@ class Daap_Api
/**
* server_info
- *
*/
public static function server_info($input)
{
@@ -115,16 +156,15 @@ class Daap_Api
$o .= self::tlv('dmap.supportsquery', 0);
$o .= self::tlv('dmap.itemname', 'Ampache');
$o .= self::tlv('dmap.supportsbrowse', 0);
- $o .= self::tlv('dmap.protocolversion', '0.2.0.0');
+ $o .= self::tlv('dmap.protocolversion', '0.2.0.0');
$o .= self::tlv('dmap.databasescount', 1);
-
+
$o = self::tlv('dmap.serverinforesponse', $o);
self::apiOutput($o);
}
/**
* content_codes
- *
*/
public static function content_codes($input)
{
@@ -132,32 +172,33 @@ class Daap_Api
foreach (self::$tags as $name => $tag) {
$entry = self::tlv('dmap.contentcodesname', $name);
$pcode = str_split($tag['code']);
- $icode = (ord($pcode[0])<<24) + (ord($pcode[1])<<16) + (ord($pcode[2])<<8) + ord($pcode[3]);
+ $icode = (ord($pcode[0]) << 24) + (ord($pcode[1]) << 16) + (ord($pcode[2]) << 8) + ord($pcode[3]);
$entry .= self::tlv('dmap.contentcodesnumber', $icode);
$entry .= self::tlv('dmap.contentcodestype', self::get_type_id($tag['type']));
$o .= self::tlv('dmap.dictionary', $entry);
}
-
+
$o = self::tlv('dmap.contentcodesresponse', $o);
self::apiOutput($o);
}
/**
* login
- *
*/
public static function login($input)
{
self::check_auth('dmap.loginresponse');
-
+
// Create a new daap session
$sql = "INSERT INTO `daap_session` (`creationdate`) VALUES (?)";
- Dba::write($sql, array(time()));
+ Dba::write($sql, array(
+ time()
+ ));
$sid = Dba::insert_id();
-
+
$o = self::tlv('dmap.status', 200);
$o .= self::tlv('dmap.sessionid', $sid);
-
+
$o = self::tlv('dmap.loginresponse', $o);
self::apiOutput($o);
}
@@ -166,17 +207,20 @@ class Daap_Api
{
// Purge expired sessions
$sql = "DELETE FROM `daap_session` WHERE `creationdate` < ?";
- Dba::write($sql, array(time() - 1800));
-
+ Dba::write($sql, array(
+ time() - 1800
+ ));
+
self::check_auth($code);
-
- if (!isset($_GET['session-id'])) {
+
+ if (! isset($_GET['session-id'])) {
debug_event('daap', 'Missing session id.', '');
} else {
-
- $sql = "SELECT * FROM `daap_session` WHERE `id` = ?";
- $db_results = Dba::read($sql, array($_GET['session-id']));
-
+ $sql = "SELECT * FROM `daap_session` WHERE `id` = ?";
+ $db_results = Dba::read($sql, array(
+ $_GET['session-id']
+ ));
+
if (Dba::num_rows($db_results) == 0) {
debug_event('daap', 'Unknown session id `' . $_GET['session-id'] . '`.', '4');
}
@@ -186,13 +230,13 @@ class Daap_Api
private static function check_auth($code = '')
{
$authenticated = false;
- $pass = AmpConfig::get('daap_pass');
+ $pass = AmpConfig::get('daap_pass');
// DAAP password specified, need to authenticate the client
- if (!empty($pass)) {
+ if (! empty($pass)) {
$headers = apache_request_headers();
- $auth = $headers['Authorization'];
+ $auth = $headers['Authorization'];
if (strpos(strtolower($auth), 'basic') === 0) {
- $decauth = base64_decode(substr($auth, 6));
+ $decauth = base64_decode(substr($auth, 6));
$userpass = split(':', $decauth);
if (count($userpass) == 2) {
if ($userpass[1] == $pass) {
@@ -203,10 +247,10 @@ class Daap_Api
} else {
$authenticated = true;
}
-
- if (!$authenticated) {
+
+ if (! $authenticated) {
debug_event('daap', 'Authentication failed. Wrong DAAP password?', '5');
- if (!empty($code)) {
+ if (! empty($code)) {
self::createApiError($code, 403);
}
}
@@ -214,96 +258,101 @@ class Daap_Api
/**
* logout
- *
*/
public static function logout($input)
{
self::check_auth();
-
+
$sql = "DELETE FROM `daap_session` WHERE `id` = ?";
- Dba::write($sql, array($input['session-id']));
-
+ Dba::write($sql, array(
+ $input['session-id']
+ ));
+
self::setHeaders();
header("HTTP/1.0 204 Logout Successful", true, 204);
}
/**
* update
- *
*/
public static function update($input)
{
self::check_session('dmap.updateresponse');
-
+
$o = self::tlv('dmap.serverrevision', Catalog::getLastUpdate());
$o .= self::tlv('dmap.status', 200);
-
+
$o = self::tlv('dmap.updateresponse', $o);
self::apiOutput($o);
}
+
+ private static function catalog_songs()
+ {
+ // $type = $_GET['type'];
+ $meta = explode(',', strtolower($_GET['meta']));
+ $o = self::tlv('dmap.status', 200);
+ $o .= self::tlv('dmap.updatetype', 0);
+
+ $songs = array();
+ $catalogs = Catalog::get_catalogs();
+ foreach ($catalogs as $catalog_id) {
+ $catalog = Catalog::create_from_id($catalog_id);
+ $songs = array_merge($songs, $catalog->get_songs());
+ }
+
+ $o .= self::tlv('dmap.specifiedtotalcount', count($songs));
+ $o .= self::tlv('dmap.returnedcount', count($songs));
+ $o .= self::tlv('dmap.listing', self::tlv_songs($songs, $meta));
+
+ return $o;
+ }
/**
- * update
- *
+ * databases
*/
public static function databases($input)
{
- //$revision = $_GET['revision-number'];
-
+ // $revision = $_GET['revision-number'];
$o = '';
// Database list
if (count($input) == 0) {
self::check_session('daap.serverdatabases');
-
+
$o = self::tlv('dmap.status', 200);
$o .= self::tlv('dmap.updatetype', 0);
$o .= self::tlv('dmap.specifiedtotalcount', 1);
$o .= self::tlv('dmap.returnedcount', 1);
-
+
$r = self::tlv('dmap.itemid', 1);
+ $r .= self::tlv('dmap.persistentid', 1);
$r .= self::tlv('dmap.itemname', 'Ampache');
$counts = Catalog::count_medias();
$r .= self::tlv('dmap.itemcount', $counts['songs']);
$r .= self::tlv('dmap.containercount', count(Playlist::get_playlists()));
$r = self::tlv('dmap.listingitem', $r);
$o .= self::tlv('dmap.listing', $r);
-
+
$o = self::tlv('daap.serverdatabases', $o);
} elseif (count($input) == 2) {
if ($input[1] == 'items') {
// Songs list
- self::check_session('daap.playlistsongs');
-
- //$type = $_GET['type'];
- $meta = explode(',', strtolower($_GET['meta']));
- $o = self::tlv('dmap.status', 200);
- $o .= self::tlv('dmap.updatetype', 0);
-
- $songs = array();
- $catalogs = Catalog::get_catalogs();
- foreach ($catalogs as $catalog_id) {
- $catalog = Catalog::create_from_id($catalog_id);
- $songs = array_merge($songs, $catalog->get_songs());
- }
-
- $o .= self::tlv('dmap.specifiedtotalcount', count($songs));
- $o .= self::tlv('dmap.returnedcount', count($songs));
- $o .= self::tlv('dmap.listing', self::tlv_songs($songs, $meta));
-
- $o = self::tlv('daap.playlistsongs', $o);
+ self::check_session('daap.databasesongs');
+
+ $o = self::catalog_songs();
+ $o = self::tlv('daap.databasesongs', $o);
} elseif ($input[1] == 'containers') {
// Playlist list
self::check_session('daap.databaseplaylists');
-
+
$o = self::tlv('dmap.status', 200);
$o .= self::tlv('dmap.updatetype', 0);
-
+
$playlists = Playlist::get_playlists();
- $searches = Search::get_searches();
- $o .= self::tlv('dmap.specifiedtotalcount', count($playlists) + count($searches));
- $o .= self::tlv('dmap.returnedcount', count($playlists) + count($searches));
-
- $l = '';
+ $searches = Search::get_searches();
+ $o .= self::tlv('dmap.specifiedtotalcount', count($playlists) + count($searches) + 1);
+ $o .= self::tlv('dmap.returnedcount', count($playlists) + count($searches) + 1);
+
+ $l = self::base_library();
foreach ($playlists as $playlist_id) {
$playlist = new Playlist($playlist_id);
$playlist->format();
@@ -315,7 +364,7 @@ class Daap_Api
$l .= self::tlv_playlist($playlist);
}
$o .= self::tlv('dmap.listing', $l);
-
+
$o = self::tlv('daap.databaseplaylists', $o);
}
} elseif (count($input) == 3) {
@@ -323,140 +372,160 @@ class Daap_Api
if ($input[1] == 'items') {
$finfo = explode('.', $input[2]);
if (count($finfo) == 2) {
- $id = intval($finfo[0]);
+ $id = intval($finfo[0]);
$type = $finfo[1];
-
- $params = '';
+
+ $params = '';
$headers = apache_request_headers();
- $client = $headers['User-Agent'];
- if (!empty($client)) {
+ $client = $headers['User-Agent'];
+ if (! empty($client)) {
$params .= '&client=' . $client;
}
$params .= '&transcode_to=' . $type;
$url = Song::play_url($id, $params, 'api', true);
self::follow_stream($url);
- exit;
+ exit();
}
}
} elseif (count($input) == 4) {
// Playlist
if ($input[1] == 'containers' && $input[3] == 'items') {
$id = intval($input[2]);
-
+
self::check_session('daap.playlistsongs');
-
- if ($id > Daap_Api::AMPACHEID_SMARTPL) {
- $id -= Daap_Api::AMPACHEID_SMARTPL;
- $playlist = new Search($id, 'song');
+
+ if ($id == Daap_Api::BASE_LIBRARY) {
+ $o = self::catalog_songs();
+ $o = self::tlv('daap.playlistsongs', $o);
} else {
- $playlist = new Playlist($id);
- }
+ if ($id > Daap_Api::AMPACHEID_SMARTPL) {
+ $id -= Daap_Api::AMPACHEID_SMARTPL;
+ $playlist = new Search($id, 'song');
+ } else {
+ $playlist = new Playlist($id);
+ }
- if ($playlist->id) {
- $meta = explode(',', strtolower($_GET['meta']));
- $o = self::tlv('dmap.status', 200);
- $o .= self::tlv('dmap.updatetype', 0);
- $items = $playlist->get_items();
- $song_ids = array();
- foreach ($items as $item) {
- if ($item['object_type'] == 'song') {
- $song_ids[] = $item['object_id'];
+ if ($playlist->id) {
+ $meta = explode(',', strtolower($_GET['meta']));
+ $o = self::tlv('dmap.status', 200);
+ $o .= self::tlv('dmap.updatetype', 0);
+ $items = $playlist->get_items();
+ $song_ids = array();
+ foreach ($items as $item) {
+ if ($item['object_type'] == 'song') {
+ $song_ids[] = $item['object_id'];
+ }
}
- }
- if (AmpConfig::get('memory_cache')) {
- Song::build_cache($song_ids);
- }
- $songs = array();
- foreach ($song_ids as $song_id) {
- $songs[] = new Song($song_id);
- }
- $o .= self::tlv('dmap.specifiedtotalcount', count($songs));
- $o .= self::tlv('dmap.returnedcount', count($songs));
- $o .= self::tlv('dmap.listing', self::tlv_songs($songs, $meta));
+ if (AmpConfig::get('memory_cache')) {
+ Song::build_cache($song_ids);
+ }
+ $songs = array();
+ foreach ($song_ids as $song_id) {
+ $songs[] = new Song($song_id);
+ }
+ $o .= self::tlv('dmap.specifiedtotalcount', count($songs));
+ $o .= self::tlv('dmap.returnedcount', count($songs));
+ $o .= self::tlv('dmap.listing', self::tlv_songs($songs, $meta));
- $o = self::tlv('daap.databaseplaylists', $o);
- } else {
- self::createApiError('daap.playlistsongs', 500, 'Invalid playlist id: ' . $id);
+ $o = self::tlv('daap.playlistsongs', $o);
+ } else {
+ self::createApiError('daap.playlistsongs', 500, 'Invalid playlist id: ' . $id);
+ }
}
}
}
-
+
self::apiOutput($o);
}
private static function tlv_songs($songs, $meta)
{
+ if (array_search('all', $meta) > - 1) {
+ $meta = self::$metas;
+ }
$lo = '';
foreach ($songs as $song) {
$song->format();
$o = self::tlv('dmap.itemkind', 2);
$o .= self::tlv('dmap.itemid', $song->id);
-
+
foreach ($meta as $m) {
switch ($m) {
case 'dmap.itemname':
$o .= self::tlv($m, $song->f_title);
- break;
- /*case 'dmap.persistentid':
+ break;
+ case 'dmap.containeritemid':
+ /* case 'dmap.persistentid': */
$o .= self::tlv($m, $song->id);
- break;*/
+ break;
case 'daap.songalbum':
$o .= self::tlv($m, $song->f_album);
- break;
+ break;
case 'daap.songartist':
$o .= self::tlv($m, $song->f_artist);
- break;
+ break;
case 'daap.songbitrate':
$o .= self::tlv($m, intval($song->bitrate / 1000));
- break;
+ break;
case 'daap.songcomment':
$o .= self::tlv($m, $song->comment);
- break;
+ break;
case 'daap.songdateadded':
$o .= self::tlv($m, $song->addition_time);
- break;
+ break;
case 'daap.songdatemodified':
if ($song->update_time) {
$o .= self::tlv($m, $song->update_time);
}
- break;
+ break;
case 'daap.songdiscnumber':
$album = new Album($song->album);
$o .= self::tlv($m, $album->disk);
- break;
+ break;
case 'daap.songformat':
$o .= self::tlv($m, $song->type);
- break;
+ break;
case 'daap.songgenre':
$o .= self::tlv($m, Tag::get_display($song->tags, false, 'song'));
- break;
+ break;
case 'daap.songsamplerate':
$o .= self::tlv($m, $song->rate);
- break;
+ break;
case 'daap.songsize':
$o .= self::tlv($m, $song->size);
- break;
+ break;
case 'daap.songtime':
$o .= self::tlv($m, $song->time * 1000);
- break;
+ break;
case 'daap.songtracknumber':
$o .= self::tlv($m, $song->track);
- break;
+ break;
case 'daap.songuserrating':
- $rating = new Rating($song->id, "song");
+ $rating = new Rating($song->id, "song");
$rating_value = $rating->get_average_rating();
$o .= self::tlv($m, $rating_value);
- break;
+ break;
case 'daap.songyear':
$o .= self::tlv($m, $song->year);
- break;
+ break;
}
}
$lo .= self::tlv('dmap.listingitem', $o);
}
-
+
return $lo;
}
+
+ public static function base_library()
+ {
+ $p = self::tlv('dmap.itemid', Daap_Api::BASE_LIBRARY);
+ $p .= self::tlv('dmap.persistentid', Daap_Api::BASE_LIBRARY);
+ $p .= self::tlv('dmap.itemname', 'Music');
+ $p .= self::tlv('daap.baseplaylist', 1);
+ $stats = Catalog::count_medias();
+ $p .= self::tlv('dmap.itemcount', $stats['songs']);
+ return self::tlv('dmap.listingitem', $p);
+ }
public static function tlv_playlist($playlist)
{
@@ -464,7 +533,9 @@ class Daap_Api
if (strtolower(get_class($playlist)) == 'search') {
$isSmart = true;
}
- $p = self::tlv('dmap.itemid', (($isSmart) ? Daap_Api::AMPACHEID_SMARTPL : 0) + $playlist->id);
+ $id = (($isSmart) ? Daap_Api::AMPACHEID_SMARTPL : 0) + $playlist->id;
+ $p = self::tlv('dmap.itemid', $id);
+ $p .= self::tlv('dmap.persistentid', $id);
$p .= self::tlv('dmap.itemname', $playlist->f_name);
$p .= self::tlv('dmap.itemcount', count($playlist->get_items()));
if ($isSmart) {
@@ -502,7 +573,7 @@ class Daap_Api
} else {
debug_event('daap', 'Unknown DAAP tag `' . $tag . '`.', '5');
}
-
+
return '';
}
@@ -516,36 +587,36 @@ class Daap_Api
// Really?! PHP...
// Need to split value into two 32-bit integer because php pack function doesn't support 64-bit integer...
$highMap = 0xffffffff00000000;
- $lowMap = 0x00000000ffffffff;
- $higher = ($value & $highMap) >>32;
- $lower = $value & $lowMap;
- return $tag . "\0\0\0\8" . pack("NN", $higher, $lower);
+ $lowMap = 0x00000000ffffffff;
+ $higher = ($value & $highMap) >> 32;
+ $lower = $value & $lowMap;
+ return $tag . "\x00\x00\x00\x08" . pack("NN", $higher, $lower);
}
private static function tlv_int($tag, $value)
{
- return $tag . "\0\0\0\4" . pack("N", $value);
+ return $tag . "\x00\x00\x00\x04" . pack("N", $value);
}
private static function tlv_short($tag, $value)
{
- return $tag . "\0\0\0\2" . pack("n", $value);
+ return $tag . "\x00\x00\x00\x02" . pack("n", $value);
}
private static function tlv_byte($tag, $value)
{
- return $tag . "\0\0\0\1" . pack("C", $value);
+ return $tag . "\x00\x00\x00\x01" . pack("C", $value);
}
private static function tlv_version($tag, $value)
{
$v = explode('.', $value);
if (count($v) == 4) {
- return $tag . "\0\0\0\4" . pack("C", $v[0]) . pack("C", $v[1]) . pack("C", $v[2]) . pack("C", $v[3]);
+ return $tag . "\x00\x00\x00\x04" . pack("C", $v[0]) . pack("C", $v[1]) . pack("C", $v[2]) . pack("C", $v[3]);
} else {
debug_event('daap', 'Malformed `' . $tag . '` version `' . $value . '`.', '5');
}
-
+
return '';
}
@@ -561,25 +632,25 @@ class Daap_Api
public static function create_dictionary()
{
- self::add_dict('mdcl', 'list', 'dmap.dictionary'); // a dictionary entry
- self::add_dict('mstt', 'int', 'dmap.status'); // the response status code, these appear to be http status codes
- self::add_dict('miid', 'int', 'dmap.itemid'); // an item's id
- self::add_dict('minm', 'string', 'dmap.itemname'); // an items name
- self::add_dict('mikd', 'byte', 'dmap.itemkind'); // the kind of item. So far, only '2' has been seen, an audio file?
- self::add_dict('mper', 'long', 'dmap.persistentid'); // a persistent id
- self::add_dict('mcon', 'list', 'dmap.container'); // an arbitrary container
- self::add_dict('mcti', 'int', 'dmap.containeritemid'); // the id of an item in its container
+ self::add_dict('mdcl', 'list', 'dmap.dictionary'); // a dictionary entry
+ self::add_dict('mstt', 'int', 'dmap.status'); // the response status code, these appear to be http status codes
+ self::add_dict('miid', 'int', 'dmap.itemid'); // an item's id
+ self::add_dict('minm', 'string', 'dmap.itemname'); // an items name
+ self::add_dict('mikd', 'byte', 'dmap.itemkind'); // the kind of item. So far, only '2' has been seen, an audio file?
+ self::add_dict('mper', 'long', 'dmap.persistentid'); // a persistent id
+ self::add_dict('mcon', 'list', 'dmap.container'); // an arbitrary container
+ self::add_dict('mcti', 'int', 'dmap.containeritemid'); // the id of an item in its container
self::add_dict('mpco', 'int', 'dmap.parentcontainerid');
self::add_dict('msts', 'string', 'dmap.statusstring');
- self::add_dict('mimc', 'int', 'dmap.itemcount'); // number of items in a container
- self::add_dict('mrco', 'int', 'dmap.returnedcount'); // number of items returned in a request
- self::add_dict('mtco', 'int', 'dmap.specifiedtotalcount'); // number of items in response to a request
+ self::add_dict('mimc', 'int', 'dmap.itemcount'); // number of items in a container
+ self::add_dict('mrco', 'int', 'dmap.returnedcount'); // number of items returned in a request
+ self::add_dict('mtco', 'int', 'dmap.specifiedtotalcount'); // number of items in response to a request
self::add_dict('mctc', 'int', 'dmap.containercount');
- self::add_dict('mlcl', 'list', 'dmap.listing'); // a list
- self::add_dict('mlit', 'list', 'dmap.listingitem'); // a single item in said list
+ self::add_dict('mlcl', 'list', 'dmap.listing'); // a list
+ self::add_dict('mlit', 'list', 'dmap.listingitem'); // a single item in said list
self::add_dict('mbcl', 'list', 'dmap.bag');
self::add_dict('mdcl', 'list', 'dmap.dictionary');
- self::add_dict('msrv', 'list', 'dmap.serverinforesponse'); // response to a /server-info
+ self::add_dict('msrv', 'list', 'dmap.serverinforesponse'); // response to a /server-info
self::add_dict('msau', 'byte', 'dmap.authenticationmethod');
self::add_dict('mslr', 'byte', 'dmap.loginrequired');
self::add_dict('mpro', 'version', 'dmap.protocolversion');
@@ -594,23 +665,23 @@ class Daap_Api
self::add_dict('msrs', 'byte', 'dmap.supportsresolve');
self::add_dict('mstm', 'int', 'dmap.timeoutinterval');
self::add_dict('msdc', 'int', 'dmap.databasescount');
- self::add_dict('mccr', 'list', 'dmap.contentcodesresponse'); // response to a /content-codes
- self::add_dict('mcnm', 'int', 'dmap.contentcodesnumber'); // the four letter code
- self::add_dict('mcna', 'string', 'dmap.contentcodesname'); // the full name of the code
- self::add_dict('mcty', 'short', 'dmap.contentcodestype'); // the type of the code
- self::add_dict('mlog', 'list', 'dmap.loginresponse'); // response to a /login
- self::add_dict('mlid', 'int', 'dmap.sessionid'); // the session id for the login session
- self::add_dict('mupd', 'list', 'dmap.updateresponse'); // response to a /update
- self::add_dict('musr', 'int', 'dmap.serverrevision'); // revision to use for requests
+ self::add_dict('mccr', 'list', 'dmap.contentcodesresponse'); // response to a /content-codes
+ self::add_dict('mcnm', 'int', 'dmap.contentcodesnumber'); // the four letter code
+ self::add_dict('mcna', 'string', 'dmap.contentcodesname'); // the full name of the code
+ self::add_dict('mcty', 'short', 'dmap.contentcodestype'); // the type of the code
+ self::add_dict('mlog', 'list', 'dmap.loginresponse'); // response to a /login
+ self::add_dict('mlid', 'int', 'dmap.sessionid'); // the session id for the login session
+ self::add_dict('mupd', 'list', 'dmap.updateresponse'); // response to a /update
+ self::add_dict('musr', 'int', 'dmap.serverrevision'); // revision to use for requests
self::add_dict('muty', 'byte', 'dmap.updatetype');
- self::add_dict('mudl', 'list', 'dmap.deletedidlisting'); // used in updates?
- self::add_dict('avdb', 'list', 'daap.serverdatabases'); // response to a /databases
+ self::add_dict('mudl', 'list', 'dmap.deletedidlisting'); // used in updates?
+ self::add_dict('avdb', 'list', 'daap.serverdatabases'); // response to a /databases
self::add_dict('abpro', 'list', 'daap.databasebrowse');
self::add_dict('abal', 'list', 'daap.browsealbumlisting');
self::add_dict('abar', 'list', 'daap.browseartistlisting');
self::add_dict('abcp', 'list', 'daap.browsecomposerlisting');
self::add_dict('abgn', 'list', 'daap.browsegenrelisting');
- self::add_dict('adbs', 'list', 'daap.databasesongs'); // response to a /databases/id/items
+ self::add_dict('adbs', 'list', 'daap.databasesongs'); // response to a /databases/id/items
self::add_dict('asal', 'string', 'daap.songalbum');
self::add_dict('asar', 'string', 'daap.songartist');
self::add_dict('asbt', 'short', 'daap.songsbeatsperminute');
@@ -629,18 +700,18 @@ class Daap_Api
self::add_dict('asrv', 'byte', 'daap.songrelativevolume');
self::add_dict('assr', 'int', 'daap.songsamplerate');
self::add_dict('assz', 'int', 'daap.songsize');
- self::add_dict('asst', 'int', 'daap.songstarttime'); // in milliseconds
- self::add_dict('assp', 'int', 'daap.songstoptime'); // in milliseconds
- self::add_dict('astm', 'int', 'daap.songtime'); // in milliseconds
+ self::add_dict('asst', 'int', 'daap.songstarttime'); // in milliseconds
+ self::add_dict('assp', 'int', 'daap.songstoptime'); // in milliseconds
+ self::add_dict('astm', 'int', 'daap.songtime'); // in milliseconds
self::add_dict('astc', 'short', 'daap.songtrackcount');
self::add_dict('astn', 'short', 'daap.songtracknumber');
self::add_dict('asur', 'byte', 'daap.songuserrating');
self::add_dict('asyr', 'short', 'daap.songyear');
self::add_dict('asdk', 'byte', 'daap.songdatakind');
self::add_dict('asul', 'string', 'daap.songdataurl');
- self::add_dict('aply', 'list', 'daap.databaseplaylists'); // response to a /databases/id/containers
+ self::add_dict('aply', 'list', 'daap.databaseplaylists'); // response to a /databases/id/containers
self::add_dict('abpl', 'byte', 'daap.baseplaylist');
- self::add_dict('apso', 'list', 'daap.playlistsongs'); // response to a /databases/id/containers/id/items
+ self::add_dict('apso', 'list', 'daap.playlistsongs'); // response to a /databases/id/containers/id/items
self::add_dict('prsv', 'list', 'daap.resolve');
self::add_dict('arif', 'list', 'daap.resolveinfo');
self::add_dict('aeNV', 'int', 'com.apple.itunes.norm-volume');
@@ -649,7 +720,8 @@ class Daap_Api
private static function add_dict($code, $type, $name)
{
- self::$tags[$name] = array('type' => $type,
+ self::$tags[$name] = array(
+ 'type' => $type,
'code' => $code
);
}
@@ -675,7 +747,7 @@ class Daap_Api
return 8;
case 'string':
return 9;
- case 'date': // represented as a 4 byte integer
+ case 'date': // represented as a 4 byte integer
return 10;
case 'version': // represented as a 4 singles bytes, e.g. 0.1.0.0 or as two shorts, e.g. 1.0
return 11;
@@ -698,7 +770,7 @@ class Daap_Api
public static function apiOutput($string)
{
self::setHeaders();
-
+
if ($_SERVER['REQUEST_METHOD'] != 'OPTIONS') {
header("Content-length: " . strlen($string));
echo $string;
@@ -715,23 +787,23 @@ class Daap_Api
case 404:
$error = "Not Found";
break;
-
+
case 401:
$error = "Unauthorized";
break;
}
header("Content-type: text/html", true);
- header("HTTP/1.0 ". $code . " " . $error, true, $code);
-
+ header("HTTP/1.0 " . $code . " " . $error, true, $code);
+
$html = "" . $error . "
" . $code . " " . $error . "
";
self::apiOutput($html);
exit();
}
- public static function createApiError($tag, $code, $msg='')
+ public static function createApiError($tag, $code, $msg = '')
{
$o = self::tlv('dmap.status', $code);
- if (!empty($msg)) {
+ if (! empty($msg)) {
$o .= self::tlv('dmap.statusstring', $msg);
}
$o = self::tlv($tag, $o);
diff --git a/sources/lib/class/database_object.abstract.php b/sources/lib/class/database_object.abstract.php
index 6b98433..1aeb01f 100644
--- a/sources/lib/class/database_object.abstract.php
+++ b/sources/lib/class/database_object.abstract.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -45,23 +45,26 @@ abstract class database_object
$table_name = $table_name ? Dba::escape($table_name) : Dba::escape(strtolower(get_class($this)));
// Make sure we've got a real id
- if (!is_numeric($id)) { return array(); }
+ if (!is_numeric($id)) {
+ return array();
+ }
if (self::is_cached($table_name,$id)) {
return self::get_from_cache($table_name,$id);
}
- $sql = "SELECT * FROM `$table_name` WHERE `id`='$id'";
+ $sql = "SELECT * FROM `$table_name` WHERE `id`='$id'";
$db_results = Dba::read($sql);
- if (!$db_results) { return array(); }
+ if (!$db_results) {
+ return array();
+ }
$row = Dba::fetch_assoc($db_results);
self::add_to_cache($table_name,$id,$row);
return $row;
-
} // get_info
/**
@@ -79,10 +82,11 @@ abstract class database_object
public static function is_cached($index, $id)
{
// Make sure we've got some parents here before we dive below
- if (!isset(self::$object_cache[$index])) { return false; }
+ if (!isset(self::$object_cache[$index])) {
+ return false;
+ }
return isset(self::$object_cache[$index][$id]);
-
} // is_cached
/**
@@ -98,7 +102,6 @@ abstract class database_object
}
return false;
-
} // get_from_cache
/**
@@ -107,11 +110,12 @@ abstract class database_object
*/
public static function add_to_cache($index, $id, $data)
{
- if (!self::$_enabled) { return false; }
+ if (!self::$_enabled) {
+ return false;
+ }
- $value = is_null($data) ? false : $data;
+ $value = is_null($data) ? false : $data;
self::$object_cache[$index][$id] = $value;
-
} // add_to_cache
/**
@@ -124,7 +128,6 @@ abstract class database_object
if (isset(self::$object_cache[$index]) && isset(self::$object_cache[$index][$id])) {
unset(self::$object_cache[$index][$id]);
}
-
} // remove_from_cache
/**
@@ -134,7 +137,6 @@ abstract class database_object
public static function _auto_init()
{
self::$_enabled = AmpConfig::get('memory_cache');
-
} // _auto_init
-
} // end database_object
+
diff --git a/sources/lib/class/dba.class.php b/sources/lib/class/dba.class.php
index 2a85f46..b9a397d 100644
--- a/sources/lib/class/dba.class.php
+++ b/sources/lib/class/dba.class.php
@@ -2,26 +2,28 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
/* Make sure they aren't directly accessing it */
-if (!defined('INIT_LOADED') || INIT_LOADED != '1') { exit; }
+if (!defined('INIT_LOADED') || INIT_LOADED != '1') {
+ exit;
+}
/**
* Dba Class
@@ -48,7 +50,6 @@ class Dba
private function __construct()
{
// Rien a faire
-
} // construct
/**
@@ -93,12 +94,14 @@ class Dba
self::$_error = json_encode($dbh->errorInfo());
debug_event('Dba', 'Error: ' . json_encode($dbh->errorInfo()), 1);
self::disconnect();
- } else if ($stmt->errorCode() && $stmt->errorCode() != '00000') {
- self::$_error = json_encode($stmt->errorInfo());
- debug_event('Dba', 'Error: ' . json_encode($stmt->errorInfo()), 1);
- self::finish($stmt);
- self::disconnect();
- return false;
+ } else {
+ if ($stmt->errorCode() && $stmt->errorCode() != '00000') {
+ self::$_error = json_encode($stmt->errorInfo());
+ debug_event('Dba', 'Error: ' . json_encode($stmt->errorInfo()), 1);
+ self::finish($stmt);
+ self::disconnect();
+ return false;
+ }
}
return $stmt;
@@ -185,6 +188,24 @@ class Dba
return $result;
}
+ public static function fetch_object($resource, $class = 'stdClass', $finish = true)
+ {
+ if (!$resource) {
+ return array();
+ }
+
+ $result = $resource->fetchObject($class);
+
+ if (!$result) {
+ if ($finish) {
+ self::finish($resource);
+ }
+ return array();
+ }
+
+ return $result;
+ }
+
/**
* num_rows
*
@@ -243,7 +264,7 @@ class Dba
$username = AmpConfig::get('database_username');
$hostname = AmpConfig::get('database_hostname');
$password = AmpConfig::get('database_password');
- $port = AmpConfig::get('database_port');
+ $port = AmpConfig::get('database_port');
// Build the data source name
if (strpos($hostname, '/') === 0) {
@@ -318,7 +339,7 @@ class Dba
*/
public static function check_database_inserted()
{
- $sql = "DESCRIBE session";
+ $sql = "DESCRIBE session";
$db_results = Dba::read($sql);
if (!$db_results) {
@@ -428,39 +449,39 @@ class Dba
switch (strtoupper($charset)) {
case 'CP1250':
case 'WINDOWS-1250':
- $target_charset = 'cp1250';
+ $target_charset = 'cp1250';
$target_collation = 'cp1250_general_ci';
break;
case 'ISO-8859':
case 'ISO-8859-2':
- $target_charset = 'latin2';
+ $target_charset = 'latin2';
$target_collation = 'latin2_general_ci';
break;
case 'ISO-8859-1':
case 'CP1252':
case 'WINDOWS-1252':
- $target_charset = 'latin1';
+ $target_charset = 'latin1';
$target_collation = 'latin1_general_ci';
break;
case 'EUC-KR':
- $target_charset = 'euckr';
+ $target_charset = 'euckr';
$target_collation = 'euckr_korean_ci';
break;
case 'CP932':
- $target_charset = 'sjis';
+ $target_charset = 'sjis';
$target_collation = 'sjis_japanese_ci';
break;
case 'KOI8-U':
- $target_charset = 'koi8u';
+ $target_charset = 'koi8u';
$target_collation = 'koi8u_general_ci';
break;
case 'KOI8-R':
- $target_charset = 'koi8r';
+ $target_charset = 'koi8r';
$target_collation = 'koi8r_general_ci';
break;
case 'UTF-8':
default:
- $target_charset = 'utf8';
+ $target_charset = 'utf8';
$target_collation = 'utf8_unicode_ci';
break;
}
@@ -482,19 +503,19 @@ class Dba
public static function reset_db_charset()
{
$translated_charset = self::translate_to_mysqlcharset(AmpConfig::get('site_charset'));
- $target_charset = $translated_charset['charset'];
- $target_collation = $translated_charset['collation'];
+ $target_charset = $translated_charset['charset'];
+ $target_collation = $translated_charset['collation'];
// Alter the charset for the entire database
$sql = "ALTER DATABASE `" . AmpConfig::get('database_name') . "` DEFAULT CHARACTER SET $target_charset COLLATE $target_collation";
Dba::write($sql);
- $sql = "SHOW TABLES";
+ $sql = "SHOW TABLES";
$db_results = Dba::read($sql);
// Go through the tables!
while ($row = Dba::fetch_row($db_results)) {
- $sql = "DESCRIBE `" . $row['0'] . "`";
+ $sql = "DESCRIBE `" . $row['0'] . "`";
$describe_results = Dba::read($sql);
// Change the tables default charset and colliation
@@ -507,7 +528,7 @@ class Dba
(strpos($table['Type'], 'varchar') !== false) ||
(strpos($table['Type'], 'enum') !== false) ||
(strpos($table['Table'],'text') !== false)) {
- $sql = "ALTER TABLE `" . $row['0'] . "` MODIFY `" . $table['Field'] . "` " . $table['Type'] . " CHARACTER SET " . $target_charset;
+ $sql = "ALTER TABLE `" . $row['0'] . "` MODIFY `" . $table['Field'] . "` " . $table['Type'] . " CHARACTER SET " . $target_charset;
$charset_results = Dba::write($sql);
if (!$charset_results) {
debug_event('CHARSET','Unable to update the charset of ' . $table['Field'] . '.' . $table['Type'] . ' to ' . $target_charset,'3');
@@ -528,7 +549,7 @@ class Dba
*/
public static function optimize_tables()
{
- $sql = "SHOW TABLES";
+ $sql = "SHOW TABLES";
$db_results = Dba::read($sql);
while ($row = Dba::fetch_row($db_results)) {
diff --git a/sources/lib/class/democratic.class.php b/sources/lib/class/democratic.class.php
index 96ef941..aca9f54 100644
--- a/sources/lib/class/democratic.class.php
+++ b/sources/lib/class/democratic.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -43,7 +43,7 @@ class Democratic extends Tmp_Playlist
// Build local, buy local
public $tmp_playlist;
public $object_ids = array();
- public $vote_ids = array();
+ public $vote_ids = array();
public $user_votes = array();
/**
@@ -52,14 +52,15 @@ class Democratic extends Tmp_Playlist
*/
public function __construct($id='')
{
- if (!$id) { return false; }
+ if (!$id) {
+ return false;
+ }
$info = $this->get_info($id);
foreach ($info as $key=>$value) {
$this->$key = $value;
}
-
} // constructor
/**
@@ -68,7 +69,9 @@ class Democratic extends Tmp_Playlist
*/
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) . ')';
@@ -83,7 +86,6 @@ class Democratic extends Tmp_Playlist
}
return true;
-
} // build_vote_cache
/**
@@ -93,10 +95,11 @@ class Democratic extends Tmp_Playlist
*/
public function is_enabled()
{
- if ($this->tmp_playlist) { return true; }
+ if ($this->tmp_playlist) {
+ return true;
+ }
return false;
-
} // is_enabled
/**
@@ -107,14 +110,12 @@ class Democratic extends Tmp_Playlist
{
$demo_id = Dba::escape($this->id);
- $sql = "SELECT * FROM `tmp_playlist` WHERE `session`='$demo_id'";
+ $sql = "SELECT * FROM `tmp_playlist` WHERE `session`='$demo_id'";
$db_results = Dba::read($sql);
$row = Dba::fetch_assoc($db_results);
$this->tmp_playlist = $row['id'];
-
-
} // set_parent
/**
@@ -141,7 +142,6 @@ class Democratic extends Tmp_Playlist
Preference::update_all($play_method,'clear');
return true;
-
} // set_user_preferences
/**
@@ -151,7 +151,7 @@ class Democratic extends Tmp_Playlist
public function format($details = true)
{
$this->f_cooldown = $this->cooldown . ' ' . T_('minutes');
- $this->f_primary = $this->primary ? T_('Primary') : '';
+ $this->f_primary = $this->primary ? T_('Primary') : '';
switch ($this->level) {
case '5':
@@ -170,7 +170,6 @@ class Democratic extends Tmp_Playlist
$this->f_level = T_('Admin');
break;
}
-
} // format
/**
@@ -180,7 +179,7 @@ class Democratic extends Tmp_Playlist
*/
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);
$results = array();
@@ -190,7 +189,6 @@ class Democratic extends Tmp_Playlist
}
return $results;
-
} // get_playlists
/**
@@ -204,17 +202,16 @@ class Democratic extends Tmp_Playlist
if (!$democratic_id) {
$level = Dba::escape($GLOBALS['user']->access);
- $sql = "SELECT `id` FROM `democratic` WHERE `level` <= '$level' " .
+ $sql = "SELECT `id` FROM `democratic` WHERE `level` <= '$level' " .
" ORDER BY `level` DESC,`primary` DESC";
- $db_results = Dba::read($sql);
- $row = Dba::fetch_assoc($db_results);
+ $db_results = Dba::read($sql);
+ $row = Dba::fetch_assoc($db_results);
$democratic_id = $row['id'];
}
$object = new Democratic($democratic_id);
return $object;
-
} // get_current_playlist
/**
@@ -259,7 +256,6 @@ class Democratic extends Tmp_Playlist
}
return $results;
-
} // get_items
/**
@@ -271,7 +267,6 @@ class Democratic extends Tmp_Playlist
$link = Stream::get_base_url() . 'uid=' . scrub_out($GLOBALS['user']->id) . '&demo_id=' . scrub_out($this->id);
return Stream_URL::format($link);
-
} // play_url
/**
@@ -298,15 +293,14 @@ class Democratic extends Tmp_Playlist
// from base_playlist
if ($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'];
} 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);
- $results = Dba::fetch_assoc($db_results);
+ $results = Dba::fetch_assoc($db_results);
return $results['id'];
}
-
} // get_next_object
/**
@@ -315,9 +309,9 @@ class Democratic extends Tmp_Playlist
*/
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);
- $tmp_id = Dba::escape($this->tmp_playlist);
+ $tmp_id = Dba::escape($this->tmp_playlist);
$sql = 'SELECT `id` FROM `tmp_playlist_data` ' .
"WHERE `object_type`='$object_type' AND " .
@@ -327,7 +321,6 @@ class Democratic extends Tmp_Playlist
$row = Dba::fetch_assoc($db_results);
return $row['id'];
-
} // get_uid_from_object_id
/**
@@ -343,7 +336,6 @@ class Democratic extends Tmp_Playlist
$song_ids = Stats::get_object_history($GLOBALS['user']->id, $cool_time);
return $song_ids;
-
} // get_cool_songs
/**
@@ -357,13 +349,12 @@ class Democratic extends Tmp_Playlist
{
/* Iterate through the objects if no vote, add to playlist and vote */
foreach ($items as $element) {
- $type = array_shift($element);
+ $type = array_shift($element);
$object_id = array_shift($element);
if (!$this->has_vote($object_id, $type)) {
$this->_add_vote($object_id, $type);
}
} // end foreach
-
} // vote
/**
@@ -396,7 +387,6 @@ class Democratic extends Tmp_Playlist
}
return false;
-
} // has_vote
/**
@@ -427,7 +417,7 @@ class Democratic extends Tmp_Playlist
/* Vote! */
$time = time();
- $sql = "INSERT INTO user_vote (`user`,`object_id`,`date`,`sid`) " .
+ $sql = "INSERT INTO user_vote (`user`,`object_id`,`date`,`sid`) " .
"VALUES (?, ?, ?, ?)";
Dba::write($sql, array($GLOBALS['user']->id, $results['id'], $time, session_id()));
@@ -442,7 +432,7 @@ class Democratic extends Tmp_Playlist
*/
public function remove_vote($row_id)
{
- $sql = "DELETE FROM `user_vote` WHERE `object_id` = ? ";
+ $sql = "DELETE FROM `user_vote` WHERE `object_id` = ? ";
$params = array($row_id);
if ($GLOBALS['user']->id > 0) {
$sql .= "AND `user` = ?";
@@ -457,7 +447,6 @@ class Democratic extends Tmp_Playlist
self::prune_tracks();
return true;
-
} // remove_vote
/**
@@ -475,7 +464,6 @@ class Democratic extends Tmp_Playlist
Dba::write($sql);
return true;
-
} // delete_votes
/**
@@ -488,10 +476,11 @@ class Democratic extends Tmp_Playlist
if ($row_id) {
debug_event('Democratic','Removing Votes for ' . $oid . ' of type ' . $object_type,'5');
$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;
-
} // delete_from_oid
/**
@@ -511,7 +500,6 @@ class Democratic extends Tmp_Playlist
self::prune_tracks();
return true;
-
} // delete
/**
@@ -520,18 +508,17 @@ class Democratic extends Tmp_Playlist
*/
public function update(array $data)
{
- $name = Dba::escape($data['name']);
- $base = Dba::escape($data['democratic']);
- $cool = Dba::escape($data['cooldown']);
+ $name = Dba::escape($data['name']);
+ $base = Dba::escape($data['democratic']);
+ $cool = Dba::escape($data['cooldown']);
$level = Dba::escape($data['level']);
- $default = Dba::escape($data['make_default']);
- $id = Dba::escape($this->id);
+ $default = Dba::escape($data['make_default']);
+ $id = Dba::escape($this->id);
$sql = "UPDATE `democratic` SET `name` = ?, `base_playlist` = ?,`cooldown` = ?, `primary` = ?, `level` = ? WHERE `id` = ?";
Dba::write($sql, array($name, $base, $cool, $default, $level, $id));
return true;
-
} // update
/**
@@ -543,10 +530,10 @@ class Democratic extends Tmp_Playlist
// Clean up the input
$name = Dba::escape($data['name']);
$base = Dba::escape($data['democratic']);
- $cool = Dba::escape($data['cooldown']);
+ $cool = Dba::escape($data['cooldown']);
$level = Dba::escape($data['level']);
- $default = Dba::escape($data['make_default']);
- $user = Dba::escape($GLOBALS['user']->id);
+ $default = Dba::escape($data['make_default']);
+ $user = Dba::escape($GLOBALS['user']->id);
$sql = "INSERT INTO `democratic` (`name`,`base_playlist`,`cooldown`,`level`,`user`,`primary`) " .
"VALUES ('$name','$base','$cool','$level','$user','$default')";
@@ -562,7 +549,6 @@ class Democratic extends Tmp_Playlist
}
return $db_results;
-
} // create
/**
@@ -580,7 +566,6 @@ class Democratic extends Tmp_Playlist
Dba::write($sql);
return true;
-
} // prune_tracks
/**
@@ -607,7 +592,6 @@ class Democratic extends Tmp_Playlist
self::clear_votes();
return true;
-
} // clear_playlist
/**
@@ -622,7 +606,6 @@ class Democratic extends Tmp_Playlist
Dba::write($sql);
return true;
-
} // clear_votes
/**
@@ -642,7 +625,6 @@ class Democratic extends Tmp_Playlist
$results = Dba::fetch_assoc($db_results);
parent::add_to_cache('democratic_vote', $id, $results['count']);
return $results['count'];
-
} // get_vote
/**
@@ -656,7 +638,7 @@ class Democratic extends Tmp_Playlist
return parent::get_from_cache('democratic_voters', $object_id);
}
- $sql = "SELECT `user` FROM `user_vote` WHERE `object_id` = ?";
+ $sql = "SELECT `user` FROM `user_vote` WHERE `object_id` = ?";
$db_results = Dba::read($sql, array($object_id));
$voters = array();
@@ -666,6 +648,5 @@ class Democratic extends Tmp_Playlist
parent::add_to_cache('democratic_vote', $object_id, $voters);
return $voters;
} // get_voters
-
-
} // Democratic class
+
diff --git a/sources/lib/class/graph.class.php b/sources/lib/class/graph.class.php
index 911b72b..6394065 100644
--- a/sources/lib/class/graph.class.php
+++ b/sources/lib/class/graph.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -24,18 +24,17 @@ class Graph
{
public function __construct()
{
- require_once AmpConfig::get('prefix') . '/modules/pChart/pData.class.php';
- require_once AmpConfig::get('prefix') . '/modules/pChart/pDraw.class.php';
- require_once AmpConfig::get('prefix') . '/modules/pChart/pImage.class.php';
-
+ require_once AmpConfig::get('prefix') . '/lib/vendor/szymach/c-pchart/src/Classes/pData.php';
+ require_once AmpConfig::get('prefix') . '/lib/vendor/szymach/c-pchart/src/Classes/pDraw.php';
+ require_once AmpConfig::get('prefix') . '/lib/vendor/szymach/c-pchart/src/Classes/pImage.php';
return true;
}
-
+
protected function get_sql_date_format($field, $zoom)
{
switch ($zoom) {
case 'hour':
- $df = "DATE_FORMAT(FROM_UNIXTIME(" . $field ."), '%Y-%m-%d %H:00:00')";
+ $df = "DATE_FORMAT(FROM_UNIXTIME(" . $field . "), '%Y-%m-%d %H:00:00')";
break;
case 'year':
$df = "DATE_FORMAT(FROM_UNIXTIME(" . $field . "), '%Y-01-01')";
@@ -132,7 +131,7 @@ class Graph
return $values;
}
- protected function get_all_pts($fct, pData $MyData, $id = 0, $object_type = null, $object_id = 0, $start_date = null, $end_date = null, $zoom = 'day', $show_total = true)
+ protected function get_all_pts($fct, CpChart\Classes\pData $MyData, $id = 0, $object_type = null, $object_id = 0, $start_date = null, $end_date = null, $zoom = 'day', $show_total = true)
{
$values = $this->get_all_type_pts($fct, $id, $object_type, $object_id, $start_date, $end_date, $zoom);
foreach ($values as $date => $value) {
@@ -144,7 +143,7 @@ class Graph
return $values;
}
- protected function get_user_all_pts($fct, pData $MyData, $user = 0, $object_type = null, $object_id = 0, $start_date = null, $end_date = null, $zoom = 'day')
+ protected function get_user_all_pts($fct, CpChart\Classes\pData $MyData, $user = 0, $object_type = null, $object_id = 0, $start_date = null, $end_date = null, $zoom = 'day')
{
$values = $this->get_all_pts($fct, $MyData, $user, $object_type, $object_id, $start_date, $end_date, $zoom);
@@ -153,7 +152,7 @@ class Graph
if (!$user && $ustats['users'] < 10) {
$user_ids = User::get_valid_users();
foreach ($user_ids as $user_id) {
- $u = new User($user_id);
+ $u = new User($user_id);
$user_values = $this->get_all_type_pts($fct, $user_id, $object_type, $object_id, $start_date, $end_date, $zoom);
foreach ($values as $date => $value) {
if (array_key_exists($date, $user_values)) {
@@ -167,7 +166,7 @@ class Graph
}
}
- protected function get_catalog_all_pts($fct, pData $MyData, $catalog = 0, $object_type = null, $object_id = 0, $start_date = null, $end_date = null, $zoom = 'day')
+ protected function get_catalog_all_pts($fct, CpChart\Classes\pData $MyData, $catalog = 0, $object_type = null, $object_id = 0, $start_date = null, $end_date = null, $zoom = 'day')
{
$values = $this->get_all_pts($fct, $MyData, $catalog, $object_type, $object_id, $start_date, $end_date, $zoom, false);
@@ -175,13 +174,13 @@ class Graph
if (!$catalog) {
$catalog_ids = Catalog::get_catalogs();
foreach ($catalog_ids as $catalog_id) {
- $c = Catalog::create_from_id($catalog_id);
+ $c = Catalog::create_from_id($catalog_id);
$catalog_values = $this->get_all_type_pts($fct, $catalog_id, $object_type, $object_id, $start_date, $end_date, $zoom);
- $pv = 0;
+ $pv = 0;
foreach ($values as $date => $value) {
if (array_key_exists($date, $catalog_values)) {
$value = $catalog_values[$date];
- $pv = $value;
+ $pv = $value;
} else {
$value = $pv;
}
@@ -193,9 +192,9 @@ class Graph
protected function get_user_hits_pts($user = 0, $object_type = 'song', $object_id = 0, $start_date = null, $end_date = null, $zoom = 'day')
{
- $df = $this->get_sql_date_format("`object_count`.`date`", $zoom);
+ $df = $this->get_sql_date_format("`object_count`.`date`", $zoom);
$where = $this->get_user_sql_where($user, $object_type, $object_id, $start_date, $end_date);
- $sql = "SELECT " . $df . " AS `zoom_date`, COUNT(`object_count`.`id`) AS `hits` FROM `object_count` " . $where .
+ $sql = "SELECT " . $df . " AS `zoom_date`, COUNT(`object_count`.`id`) AS `hits` FROM `object_count` " . $where .
" GROUP BY " . $df;
$db_results = Dba::read($sql);
@@ -208,9 +207,9 @@ class Graph
protected function get_user_object_count_pts($user = 0, $object_type = 'song', $object_id = 0, $start_date = null, $end_date = null, $zoom = 'day', $column = 'size')
{
- $df = $this->get_sql_date_format("`object_count`.`date`", $zoom);
+ $df = $this->get_sql_date_format("`object_count`.`date`", $zoom);
$where = $this->get_user_sql_where($user, $object_type, $object_id, $start_date, $end_date);
- $sql = "SELECT " . $df . " AS `zoom_date`, SUM(`" . $object_type . "`.`" . $column . "`) AS `total` FROM `object_count` " .
+ $sql = "SELECT " . $df . " AS `zoom_date`, SUM(`" . $object_type . "`.`" . $column . "`) AS `total` FROM `object_count` " .
" JOIN `" . $object_type . "` ON `" . $object_type . "`.`id` = `object_count`.`object_id` " . $where .
" GROUP BY " . $df;
$db_results = Dba::read($sql);
@@ -235,9 +234,9 @@ class Graph
protected function get_catalog_files_pts($catalog = 0, $object_type = 'song', $object_id = 0, $start_date = null, $end_date = null, $zoom = 'day')
{
$start_date = $start_date ?: ($end_date ?: time()) - 864000;
- $df = $this->get_sql_date_format("`" . $object_type . "`.`addition_time`", $zoom);
- $where = $this->get_catalog_sql_where($object_type, $object_id, $catalog, $start_date, $end_date);
- $sql = "SELECT " . $df . " AS `zoom_date`, ((SELECT COUNT(`t2`.`id`) FROM `" . $object_type . "` `t2` WHERE `t2`.`addition_time` < `zoom_date`) + COUNT(`" . $object_type . "`.`id`)) AS `files` FROM `" . $object_type . "` " . $where .
+ $df = $this->get_sql_date_format("`" . $object_type . "`.`addition_time`", $zoom);
+ $where = $this->get_catalog_sql_where($object_type, $object_id, $catalog, $start_date, $end_date);
+ $sql = "SELECT " . $df . " AS `zoom_date`, ((SELECT COUNT(`t2`.`id`) FROM `" . $object_type . "` `t2` WHERE `t2`.`addition_time` < `zoom_date`) + COUNT(`" . $object_type . "`.`id`)) AS `files` FROM `" . $object_type . "` " . $where .
" GROUP BY " . $df;
$db_results = Dba::read($sql);
@@ -251,9 +250,9 @@ class Graph
protected function get_catalog_size_pts($catalog = 0, $object_type = 'song', $object_id = 0, $start_date = null, $end_date = null, $zoom = 'day')
{
$start_date = $start_date ?: ($end_date ?: time()) - 864000;
- $df = $this->get_sql_date_format("`" . $object_type . "`.`addition_time`", $zoom);
- $where = $this->get_catalog_sql_where($object_type, $object_id, $catalog, $start_date, $end_date);
- $sql = "SELECT " . $df . " AS `zoom_date`, ((SELECT SUM(`t2`.`size`) FROM `" . $object_type . "` `t2` WHERE `t2`.`addition_time` < `zoom_date`) + SUM(`" . $object_type . "`.`size`)) AS `storage` FROM `" . $object_type . "` " . $where .
+ $df = $this->get_sql_date_format("`" . $object_type . "`.`addition_time`", $zoom);
+ $where = $this->get_catalog_sql_where($object_type, $object_id, $catalog, $start_date, $end_date);
+ $sql = "SELECT " . $df . " AS `zoom_date`, ((SELECT SUM(`t2`.`size`) FROM `" . $object_type . "` `t2` WHERE `t2`.`addition_time` < `zoom_date`) + SUM(`" . $object_type . "`.`size`)) AS `storage` FROM `" . $object_type . "` " . $where .
" GROUP BY " . $df;
$db_results = Dba::read($sql);
@@ -289,7 +288,7 @@ class Graph
return $pts;
}
- protected function render_graph($title, pData $MyData, $zoom, $width = 0, $height = 0)
+ protected function render_graph($title, CpChart\Classes\pData $MyData, $zoom, $width = 0, $height = 0)
{
// Check graph size sanity
$width = intval($width);
@@ -319,10 +318,10 @@ class Graph
}
/* Create the pChart object */
- $myPicture = new pImage($width,$height,$MyData);
+ $myPicture = new CpChart\Classes\pImage($width,$height,$MyData);
/* Turn of Antialiasing */
- $myPicture->Antialias = FALSE;
+ $myPicture->Antialias = false;
/* Draw a background */
$Settings = array("R"=>90, "G"=>90, "B"=>90, "Dash"=>1, "DashR"=>120, "DashG"=>120, "DashB"=>120);
@@ -336,25 +335,26 @@ class Graph
/* Add a border to the picture */
$myPicture->drawRectangle(0,0,$width-1,$height-1,array("R"=>0,"G"=>0,"B"=>0));
+ $font_path = AmpConfig::get('prefix') . "/lib/vendor/szymach/c-pchart/src/Resources/fonts";
/* Write the chart title */
- $myPicture->setFontProperties(array("FontName"=>AmpConfig::get('prefix')."/modules/pChart/fonts/Forgotte.ttf","FontSize"=>11));
+ $myPicture->setFontProperties(array("FontName"=>$font_path . "/Forgotte.ttf","FontSize"=>11));
$myPicture->drawText(150,35,$title,array("FontSize"=>20,"Align"=>TEXT_ALIGN_BOTTOMMIDDLE));
/* Set the default font */
- $myPicture->setFontProperties(array("FontName"=>AmpConfig::get('prefix')."/modules/pChart/fonts/pf_arma_five.ttf","FontSize"=>6));
+ $myPicture->setFontProperties(array("FontName"=>$font_path . "/pf_arma_five.ttf","FontSize"=>6));
/* Define the chart area */
$myPicture->setGraphArea(60,40,$width-20,$height-50);
/* Draw the scale */
- $scaleSettings = array("XMargin"=>10,"YMargin"=>10,"Floating"=>TRUE,"GridR"=>200,"GridG"=>200,"GridB"=>200,"RemoveSkippedAxis"=>TRUE,"DrawSubTicks"=>FALSE,"Mode"=>SCALE_MODE_START0,"LabelRotation"=>45,"LabelingMethod"=>LABELING_DIFFERENT);
+ $scaleSettings = array("XMargin"=>10,"YMargin"=>10,"Floating"=>true,"GridR"=>200,"GridG"=>200,"GridB"=>200,"RemoveSkippedAxis"=>true,"DrawSubTicks"=>false,"Mode"=>SCALE_MODE_START0,"LabelRotation"=>45,"LabelingMethod"=>LABELING_DIFFERENT);
$myPicture->drawScale($scaleSettings);
/* Turn on Antialiasing */
- $myPicture->Antialias = TRUE;
+ $myPicture->Antialias = true;
/* Draw the line chart */
- $myPicture->setShadow(TRUE,array("X"=>1,"Y"=>1,"R"=>0,"G"=>0,"B"=>0,"Alpha"=>10));
+ $myPicture->setShadow(true,array("X"=>1,"Y"=>1,"R"=>0,"G"=>0,"B"=>0,"Alpha"=>10));
$myPicture->drawLineChart();
/* Write a label over the chart */
@@ -370,7 +370,7 @@ class Graph
public function render_user_hits($user = 0, $object_type, $object_id, $start_date = null, $end_date = null, $zoom = 'day', $width = 0, $height = 0)
{
- $MyData = new pData();
+ $MyData = new CpChart\Classes\pData();
$this->get_user_all_pts('get_user_hits_pts', $MyData, $user, $object_type, $object_id, $start_date, $end_date, $zoom);
$MyData->setAxisName(0, "Hits");
@@ -381,7 +381,7 @@ class Graph
public function render_user_bandwidth($user = 0, $object_type = null, $object_id = 0, $start_date = null, $end_date = null, $zoom = 'day', $width = 0, $height = 0)
{
- $MyData = new pData();
+ $MyData = new CpChart\Classes\pData();
$this->get_user_all_pts('get_user_bandwidth_pts', $MyData, $user, $object_type, $object_id, $start_date, $end_date, $zoom);
$MyData->setAxisName(0, "Bandwidth");
@@ -392,7 +392,7 @@ class Graph
public function get_total_bandwidth($user = 0, $start_date = null, $end_date = null)
{
- $total = 0;
+ $total = 0;
$values = $this->get_all_type_pts('get_user_bandwidth_pts', $user, null, 0, $start_date, $end_date, 'month');
foreach ($values as $date => $value) {
$total += $value;
@@ -403,7 +403,7 @@ class Graph
public function get_total_time($user = 0, $start_date = null, $end_date = null)
{
- $total = 0;
+ $total = 0;
$values = $this->get_all_type_pts('get_user_time_pts', $user, null, 0, $start_date, $end_date, 'month');
foreach ($values as $date => $value) {
$total += $value;
@@ -414,7 +414,7 @@ class Graph
public function get_total_hits($user = 0, $start_date = null, $end_date = null)
{
- $total = 0;
+ $total = 0;
$values = $this->get_all_type_pts('get_user_hits_pts', $user, null, 0, $start_date, $end_date, 'month');
foreach ($values as $date => $value) {
$total += $value;
@@ -425,7 +425,7 @@ class Graph
public function render_catalog_files($catalog = 0, $object_type = null, $object_id = 0, $start_date = null, $end_date = null, $zoom = 'day', $width = 0, $height = 0)
{
- $MyData = new pData();
+ $MyData = new CpChart\Classes\pData();
$this->get_catalog_all_pts('get_catalog_files_pts', $MyData, $catalog, $object_type, $object_id, $start_date, $end_date, $zoom);
$MyData->setAxisName(0, "Files");
@@ -436,7 +436,7 @@ class Graph
public function render_catalog_size($catalog = 0, $object_type = null, $object_id = 0, $start_date = null, $end_date = null, $zoom = 'day', $width = 0, $height = 0)
{
- $MyData = new pData();
+ $MyData = new CpChart\Classes\pData();
$this->get_catalog_all_pts('get_catalog_size_pts', $MyData, $catalog, $object_type, $object_id, $start_date, $end_date, $zoom);
$MyData->setAxisName(0, "Size");
@@ -462,19 +462,29 @@ class Graph
public static function display_from_request()
{
- if (!Access::check('interface','50')) {
+ $object_type = $_REQUEST['object_type'];
+ $object_id = $_REQUEST['object_id'];
+
+ $libitem = null;
+ $owner_id = 0;
+ if ($object_id) {
+ if (Core::is_library_item($object_type)) {
+ $libitem = new $object_type($object_id);
+ $owner_id = $libitem->get_user_owner();
+ }
+ }
+
+ if (($owner_id <= 0 || $owner_id != $GLOBALS['user']->id) && !Access::check('interface','50')) {
UI::access_denied();
} else {
- $user_id = $_REQUEST['user_id'];
- $object_type = $_REQUEST['object_type'];
- $object_id = $_REQUEST['object_id'];
- $end_date = $_REQUEST['end_date'] ? strtotime($_REQUEST['end_date']) : time();
- $f_end_date = date("Y-m-d H:i", $end_date);
- $start_date = $_REQUEST['start_date'] ? strtotime($_REQUEST['start_date']) : ($end_date - 864000);
+ $user_id = $_REQUEST['user_id'];
+ $end_date = $_REQUEST['end_date'] ? strtotime($_REQUEST['end_date']) : time();
+ $f_end_date = date("Y-m-d H:i", $end_date);
+ $start_date = $_REQUEST['start_date'] ? strtotime($_REQUEST['start_date']) : ($end_date - 864000);
$f_start_date = date("Y-m-d H:i", $start_date);
- $zoom = $_REQUEST['zoom'] ?: 'day';
+ $zoom = $_REQUEST['zoom'] ?: 'day';
- $gtypes = array();
+ $gtypes = array();
$gtypes[] = 'user_hits';
if ($object_type == null || $object_type == 'song' || $object_type == 'video') {
$gtypes[] = 'user_bandwidth';
@@ -485,21 +495,20 @@ class Graph
}
$blink = '';
- if ($object_id) {
- if (Core::is_library_item($object_type)) {
- $libitem = new $object_type($object_id);
- $libitem->format();
- if (isset($libitem->f_link)) {
- $blink = $libitem->f_link;
- }
+ if ($libitem !== null) {
+ $libitem->format();
+ if (isset($libitem->f_link)) {
+ $blink = $libitem->f_link;
+ }
+ } else {
+ if ($user_id) {
+ $u = new User($user_id);
+ $u->format();
+ $blink = $u->f_link;
}
- } else if ($user_id) {
- $u = new User($user_id);
- $u->format();
- $blink = $u->f_link;
}
- require_once AmpConfig::get('prefix') . '/templates/show_graphs.inc.php';
+ require_once AmpConfig::get('prefix') . UI::find_template('show_graphs.inc.php');
}
}
}
diff --git a/sources/lib/class/label.class.php b/sources/lib/class/label.class.php
index f469b82..941f2fd 100644
--- a/sources/lib/class/label.class.php
+++ b/sources/lib/class/label.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -85,7 +85,9 @@ class Label extends database_object implements library_item
*/
public function __construct($id=null)
{
- if (!$id) { return false; }
+ if (!$id) {
+ return false;
+ }
$info = $this->get_info($id);
foreach ($info as $key=>$value) {
@@ -117,7 +119,7 @@ class Label extends database_object implements library_item
public function get_childrens()
{
- $medias = array();
+ $medias = array();
$artists = $this->get_artists();
foreach ($artists as $artist_id) {
$medias[] = array(
@@ -145,7 +147,7 @@ class Label extends database_object implements library_item
public function get_keywords()
{
- $keywords = array();
+ $keywords = array();
$keywords['label'] = array('important' => true,
'label' => T_('Label'),
'value' => $this->f_name);
@@ -179,11 +181,11 @@ class Label extends database_object implements library_item
public function search_childrens($name)
{
- $search['type'] = "artist";
- $search['rule_0_input'] = $name;
+ $search['type'] = "artist";
+ $search['rule_0_input'] = $name;
$search['rule_0_operator'] = 4;
- $search['rule_0'] = "title";
- $artists = Search::run($search);
+ $search['rule_0'] = "title";
+ $artists = Search::run($search);
$childrens = array();
foreach ($artists as $artist) {
@@ -201,12 +203,14 @@ class Label extends database_object implements library_item
$user = $GLOBALS['user']->id;
}
- if (!$user)
+ if (!$user) {
return false;
+ }
if (AmpConfig::get('upload_allow_edit')) {
- if ($this->user !== null && $user == $this->user)
+ if ($this->user !== null && $user == $this->user) {
return true;
+ }
}
return Access::check('interface', 50, $user);
@@ -218,22 +222,22 @@ class Label extends database_object implements library_item
return false;
}
- $name = isset($data['name']) ? $data['name'] : $this->name;
+ $name = isset($data['name']) ? $data['name'] : $this->name;
$category = isset($data['category']) ? $data['category'] : $this->category;
- $summary = isset($data['summary']) ? $data['summary'] : $this->summary;
- $address = isset($data['address']) ? $data['address'] : $this->address;
- $email = isset($data['email']) ? $data['email'] : $this->email;
- $website = isset($data['website']) ? $data['website'] : $this->website;
+ $summary = isset($data['summary']) ? $data['summary'] : $this->summary;
+ $address = isset($data['address']) ? $data['address'] : $this->address;
+ $email = isset($data['email']) ? $data['email'] : $this->email;
+ $website = isset($data['website']) ? $data['website'] : $this->website;
$sql = "UPDATE `label` SET `name` = ?, `category` = ?, `summary` = ?, `address` = ?, `email` = ?, `website` = ? WHERE `id` = ?";
Dba::write($sql, array($name, $category, $summary, $address, $email, $website, $this->id));
- $this->name = $name;
+ $this->name = $name;
$this->category = $category;
- $this->summary = $summary;
- $this->address = $address;
- $this->email = $email;
- $this->website = $website;
+ $this->summary = $summary;
+ $this->address = $address;
+ $this->email = $email;
+ $this->website = $website;
return $this->id;
}
@@ -244,13 +248,13 @@ class Label extends database_object implements library_item
return false;
}
- $name = $data['name'];
- $category = $data['category'];
- $summary = $data['summary'];
- $address = $data['address'];
- $email = $data['email'];
- $website = $data['website'];
- $user = $data['user'] ?: $GLOBALS['user']->id;
+ $name = $data['name'];
+ $category = $data['category'];
+ $summary = $data['summary'];
+ $address = $data['address'];
+ $email = $data['email'];
+ $website = $data['website'];
+ $user = $data['user'] ?: $GLOBALS['user']->id;
$creation_date = $data['creation_date'] ?: time();
$sql = "INSERT INTO `label` (`name`, `category`, `summary`, `address`, `email`, `website`, `user`, `creation_date`) " .
@@ -263,11 +267,11 @@ class Label extends database_object implements library_item
public static function lookup(array $data, $id = 0)
{
- $ret = -1;
+ $ret = -1;
$name = trim($data['name']);
if (!empty($name)) {
- $ret = 0;
- $sql = "SELECT `id` FROM `label` WHERE `name` = ?";
+ $ret = 0;
+ $sql = "SELECT `id` FROM `label` WHERE `name` = ?";
$params = array($name);
if ($id > 0) {
$sql .= " AND `id` != ?";
@@ -289,9 +293,9 @@ class Label extends database_object implements library_item
public function get_artists()
{
- $sql = "SELECT `artist` FROM `label_asso` WHERE `label` = ?";
+ $sql = "SELECT `artist` FROM `label_asso` WHERE `label` = ?";
$db_results = Dba::read($sql, array($this->id));
- $results = array();
+ $results = array();
while ($row = Dba::fetch_assoc($db_results)) {
$results[] = $row['artist'];
}
@@ -336,18 +340,18 @@ class Label extends database_object implements library_item
}
return $results;
-
} // get_songs
public function remove()
{
- $sql = "DELETE FROM `label` WHERE `id` = ?";
+ $sql = "DELETE FROM `label` WHERE `id` = ?";
$deleted = Dba::write($sql, array($this->id));
if ($deleted) {
Art::gc('label', $this->id);
Userflag::gc('label', $this->id);
Rating::gc('label', $this->id);
Shoutbox::gc('label', $this->id);
+ Useractivity::gc('label', $this->id);
}
return $deleted;
@@ -355,9 +359,9 @@ class Label extends database_object implements library_item
public static function get_all_labels()
{
- $sql = "SELECT `id`, `name` FROM `label`";
+ $sql = "SELECT `id`, `name` FROM `label`";
$db_results = Dba::read($sql);
- $results = array();
+ $results = array();
while ($row = Dba::fetch_assoc($db_results)) {
$results[$row['id']] = $row['name'];
}
@@ -370,7 +374,7 @@ class Label extends database_object implements library_item
"LEFT JOIN `label_asso` ON `label_asso`.`label` = `label`.`id` " .
"WHERE `label_asso`.`artist` = ?";
$db_results = Dba::read($sql, array($artist_id));
- $results = array();
+ $results = array();
while ($row = Dba::fetch_assoc($db_results)) {
$results[$row['id']] = $row['name'];
}
@@ -383,7 +387,9 @@ class Label extends database_object implements library_item
*/
public static function get_display($labels, $link=false)
{
- if (!is_array($labels)) { return ''; }
+ if (!is_array($labels)) {
+ return '';
+ }
$results = '';
@@ -402,7 +408,6 @@ class Label extends database_object implements library_item
$results = rtrim($results, ', ');
return $results;
-
} // get_display
/**
@@ -411,16 +416,16 @@ class Label extends database_object implements library_item
*/
public static function update_label_list($labels_comma, $artist_id, $overwrite)
{
- debug_event('label.class', 'Updating labels for values {'.$labels_comma.'} artist {'.$artist_id.'}', '5');
+ debug_event('label.class', 'Updating labels for values {' . $labels_comma . '} artist {' . $artist_id . '}', '5');
- $clabels = Label::get_labels($artist_id);
+ $clabels = Label::get_labels($artist_id);
$editedLabels = explode(",", $labels_comma);
if (is_array($clabels)) {
foreach ($clabels as $clid => $clv) {
if ($clid) {
$clabel = new Label($clid);
- debug_event('label.class', 'Processing label {'.$clabel->name.'}...', '5');
+ debug_event('label.class', 'Processing label {' . $clabel->name . '}...', '5');
$found = false;
foreach ($editedLabels as $lk => $lv) {
@@ -433,9 +438,11 @@ class Label extends database_object implements library_item
if ($found) {
debug_event('label.class', 'Already found. Do nothing.', '5');
unset($editedLabels[$lk]);
- } else if ($overwrite) {
- debug_event('label.class', 'Not found in the new list. Delete it.', '5');
- $clabel->remove_artist_assoc($artist_id);
+ } else {
+ if ($overwrite) {
+ debug_event('label.class', 'Not found in the new list. Delete it.', '5');
+ $clabel->remove_artist_assoc($artist_id);
+ }
}
}
}
@@ -444,7 +451,7 @@ class Label extends database_object implements library_item
// Look if we need to add some new labels
foreach ($editedLabels as $lk => $lv) {
if ($lv != '') {
- debug_event('label.class', 'Adding new label {'.$lv.'}', '5');
+ debug_event('label.class', 'Adding new label {' . $lv . '}', '5');
$label_id = Label::lookup(array('name' => $lv));
if ($label_id === 0) {
debug_event('label.class', 'Creating a label directly from artist editing is not allowed.', '5');
diff --git a/sources/lib/class/library_item.interface.php b/sources/lib/class/library_item.interface.php
index 9ab85bc..67d8203 100644
--- a/sources/lib/class/library_item.interface.php
+++ b/sources/lib/class/library_item.interface.php
@@ -2,21 +2,22 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
/**
@@ -41,5 +42,5 @@ interface library_item extends playable_item
public function update(array $data);
public static function gc();
-
} // end interface
+
diff --git a/sources/lib/class/license.class.php b/sources/lib/class/license.class.php
index b026012..2cff3f9 100644
--- a/sources/lib/class/license.class.php
+++ b/sources/lib/class/license.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -56,7 +56,6 @@ class License
$this->_get_info($id);
return true;
-
} // Constructor
/**
@@ -67,7 +66,7 @@ class License
*/
private function _get_info($id)
{
- $sql = "SELECT * FROM `license` WHERE `id` = ?";
+ $sql = "SELECT * FROM `license` WHERE `id` = ?";
$db_results = Dba::read($sql, array($id));
$data = Dba::fetch_assoc($db_results);
@@ -77,7 +76,6 @@ class License
}
return true;
-
} // _get_info
/**
@@ -94,7 +92,6 @@ class License
$insert_id = Dba::insert_id();
return $insert_id;
-
} // create
/**
@@ -109,7 +106,6 @@ class License
Dba::write($sql, array($data['name'], $data['description'], $data['external_link'], $this->id));
return $this->id;
-
} // create
/**
@@ -130,7 +126,6 @@ class License
{
$sql = "DELETE FROM `license` WHERE `id` = ?";
Dba::write($sql, array($license_id));
-
} // delete
/**
@@ -140,7 +135,7 @@ class License
*/
public static function get_licenses()
{
- $sql = 'SELECT `id` from `license` ORDER BY `name`';
+ $sql = 'SELECT `id` from `license` ORDER BY `name`';
$db_results = Dba::read($sql);
$results = array();
@@ -150,5 +145,5 @@ class License
return $results;
} // get_licenses
-
} // License class
+
diff --git a/sources/lib/class/live_stream.class.php b/sources/lib/class/live_stream.class.php
index 2065f51..5285070 100644
--- a/sources/lib/class/live_stream.class.php
+++ b/sources/lib/class/live_stream.class.php
@@ -2,22 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; version 2
- * of the License.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -76,7 +75,9 @@ class Live_Stream extends database_object implements media, library_item
*/
public function __construct($id = null)
{
- if (!$id) { return false; }
+ if (!$id) {
+ return false;
+ }
$info = $this->get_info($id, 'live_stream');
@@ -84,7 +85,6 @@ class Live_Stream extends database_object implements media, library_item
foreach ($info as $key=>$value) {
$this->$key = $value;
}
-
} // constructor
/**
@@ -95,12 +95,11 @@ class Live_Stream extends database_object implements media, library_item
public function format($details = true)
{
// Default link used on the rightbar
- $this->f_link = "url . "\">" . $this->name . "";
+ $this->f_link = "url . "\">" . $this->name . "";
$this->f_name_link = "site_url . "\">" . $this->name . "";
- $this->f_url_link = "url . "\">" . $this->url . "";
+ $this->f_url_link = "url . "\">" . $this->url . "";
return true;
-
} // format
public function get_keywords()
@@ -182,7 +181,7 @@ class Live_Stream extends database_object implements media, library_item
public function update(array $data)
{
if (!$data['name']) {
- Error::add('general', T_('Name Required'));
+ AmpError::add('general', T_('Name Required'));
}
$allowed_array = array('https','http','mms','mmsh','mmsu','mmst','rtsp','rtmp');
@@ -190,10 +189,17 @@ class Live_Stream extends database_object implements media, library_item
$elements = explode(":",$data['url']);
if (!in_array($elements['0'],$allowed_array)) {
- Error::add('general', T_('Invalid URL must be mms:// , https:// or http://'));
+ AmpError::add('general', T_('Invalid URL must be mms:// , https:// or http://'));
+ }
+
+ if (!empty($data['site_url'])) {
+ $elements = explode(":", $data['site_url']);
+ if (!in_array($elements['0'], $allowed_array)) {
+ AmpError::add('site_url', T_('Invalid URL must be http:// or https://'));
+ }
}
- if (Error::occurred()) {
+ if (AmpError::occurred()) {
return false;
}
@@ -201,7 +207,6 @@ class Live_Stream extends database_object implements media, library_item
Dba::write($sql, array($data['name'], $data['site_url'], $data['url'], $data['codec'], $this->id));
return $this->id;
-
} // update
/**
@@ -213,24 +218,33 @@ class Live_Stream extends database_object implements media, library_item
{
// Make sure we've got a name
if (!strlen($data['name'])) {
- Error::add('name', T_('Name Required'));
+ AmpError::add('name', T_('Name Required'));
}
$allowed_array = array('https','http','mms','mmsh','mmsu','mmst','rtsp','rtmp');
$elements = explode(":", $data['url']);
- if (!in_array($elements['0'],$allowed_array)) {
- Error::add('url', T_('Invalid URL must be http:// or https://'));
+ if (!in_array($elements['0'], $allowed_array)) {
+ AmpError::add('url', T_('Invalid URL must be http:// or https://'));
+ }
+
+ if (!empty($data['site_url'])) {
+ $elements = explode(":", $data['site_url']);
+ if (!in_array($elements['0'], $allowed_array)) {
+ AmpError::add('site_url', T_('Invalid URL must be http:// or https://'));
+ }
}
// Make sure it's a real catalog
$catalog = Catalog::create_from_id($data['catalog']);
if (!$catalog->name) {
- Error::add('catalog', T_('Invalid Catalog'));
+ AmpError::add('catalog', T_('Invalid Catalog'));
}
- if (Error::occurred()) { return false; }
+ if (AmpError::occurred()) {
+ return false;
+ }
// If we've made it this far everything must be ok... I hope
$sql = "INSERT INTO `live_stream` (`name`,`site_url`,`url`,`catalog`,`codec`) " .
@@ -238,7 +252,6 @@ class Live_Stream extends database_object implements media, library_item
$db_results = Dba::write($sql, array($data['name'], $data['site_url'], $data['url'], $catalog->id, $data['codec']));
return $db_results;
-
} // create
/**
@@ -251,7 +264,6 @@ class Live_Stream extends database_object implements media, library_item
Dba::write($sql, array($this->id));
return true;
-
} // delete
/**
@@ -272,7 +284,6 @@ class Live_Stream extends database_object implements media, library_item
$radio = new Live_Stream($oid);
return $radio->url . $additional_params;
-
} // play_url
public function get_stream_name()
@@ -305,7 +316,7 @@ class Live_Stream extends database_object implements media, library_item
$params[] = $catalog;
}
$db_results = Dba::read($sql, $params);
- $radios = array();
+ $radios = array();
while ($results = Dba::fetch_assoc($db_results)) {
$radios[] = $results['id'];
@@ -316,12 +327,11 @@ class Live_Stream extends database_object implements media, library_item
public static function gc()
{
-
}
public function set_played($user, $agent, $location)
{
// Do nothing
}
-
} //end of radio class
+
diff --git a/sources/lib/class/localplay.class.php b/sources/lib/class/localplay.class.php
index 7c78978..cba76d9 100644
--- a/sources/lib/class/localplay.class.php
+++ b/sources/lib/class/localplay.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -43,7 +43,6 @@ class Localplay
$this->type = $type;
$this->_get_info();
-
} // Localplay
/**
@@ -56,7 +55,6 @@ class Localplay
private function _get_info()
{
$this->_load_player();
-
} // _get_info
/**
@@ -71,7 +69,6 @@ class Localplay
} else {
return false;
}
-
} // player_loaded
/**
@@ -81,13 +78,13 @@ class Localplay
*/
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);
$this->f_description = $this->_player->get_description();
- $this->f_version = $this->_player->get_version();
-
-
+ $this->f_version = $this->_player->get_version();
} // format
/**
@@ -98,10 +95,12 @@ class Localplay
*/
private function _load_player()
{
- if (!$this->type) { return false; }
+ if (!$this->type) {
+ return false;
+ }
- $filename = AmpConfig::get('prefix') . '/modules/localplay/' . $this->type . '.controller.php';
- $include = require_once $filename;
+ $filename = AmpConfig::get('prefix') . '/modules/localplay/' . $this->type . '/' . $this->type . '.controller.php';
+ $include = require_once $filename;
if (!$include) {
/* Throw Error Here */
@@ -109,7 +108,7 @@ class Localplay
return false;
} // include
else {
- $class_name = "Ampache" . $this->type;
+ $class_name = "Ampache" . $this->type;
$this->_player = new $class_name();
if (!($this->_player instanceof localplay_controller)) {
debug_event('Localplay',$this->type . ' not an instance of controller abstract, unable to load','1');
@@ -117,7 +116,6 @@ class Localplay
return false;
}
}
-
} // _load_player
/**
@@ -131,7 +129,6 @@ class Localplay
$name = scrub_out($name);
$name = Ajax::text('?page=localplay&action=command&command=skip&id=' . $id,$name,'localplay_skip_' . $id);
return $name;
-
} // format_name
/**
@@ -141,7 +138,8 @@ class Localplay
public static function get_controllers()
{
/* First open the dir */
- $handle = opendir(AmpConfig::get('prefix') . '/modules/localplay');
+ $basedir = AmpConfig::get('prefix') . '/modules/localplay';
+ $handle = opendir($basedir);
if (!is_resource($handle)) {
debug_event('Localplay','Error: Unable to read localplay controller directory','1');
@@ -151,19 +149,25 @@ class Localplay
$results = array();
while (false !== ($file = readdir($handle))) {
-
- if (substr($file,-14,14) != 'controller.php') { continue; }
-
- /* Make sure it isn't a dir */
- if (!is_dir($file)) {
- /* Get the basename and then everything before controller */
- $filename = basename($file,'.controller.php');
- $results[] = $filename;
+ if ($file === '.' || $file === '..') {
+ continue;
}
+ /* Make sure it is a dir */
+ if (! is_dir($basedir . '/' . $file)) {
+ debug_event('Localplay', $file . ' is not a directory.', 3);
+ continue;
+ }
+
+ // Make sure the plugin base file exists inside the plugin directory
+ if (! file_exists($basedir . '/' . $file . '/' . $file . '.controller.php')) {
+ debug_event('Localplay', 'Missing class for ' . $file, 3);
+ continue;
+ }
+
+ $results[] = $file;
} // end while
return $results;
-
} // get_controllers
/**
@@ -176,10 +180,11 @@ class Localplay
// Load the controller and then check for its preferences
$localplay = new Localplay($controller);
// If we can't even load it no sense in going on
- if (!isset($localplay->_player)) { return false; }
+ if (!isset($localplay->_player)) {
+ return false;
+ }
return $localplay->_player->is_installed();
-
} // is_enabled
/**
@@ -193,7 +198,6 @@ class Localplay
$installed = $this->_player->install();
return $installed;
-
} // install
/**
@@ -212,7 +216,6 @@ class Localplay
}
return true;
-
} // uninstall
/**
@@ -228,7 +231,6 @@ class Localplay
}
return true;
-
} // connect
/**
@@ -244,7 +246,6 @@ class Localplay
}
return true;
-
} // play
/**
@@ -260,7 +261,6 @@ class Localplay
}
return true;
-
} // stop
/**
@@ -270,7 +270,6 @@ class Localplay
{
debug_event('localplay', 'Deprecated add method called: ' . json_encode($object), 5);
return false;
-
} // add
/**
@@ -285,7 +284,6 @@ class Localplay
}
return true;
-
} // add_url
/**
@@ -302,7 +300,6 @@ class Localplay
}
return $data;
-
} // repeat
/**
@@ -319,7 +316,6 @@ class Localplay
}
return $data;
-
} // random
/**
@@ -337,7 +333,6 @@ class Localplay
}
return $data;
-
} // status
/**
@@ -350,13 +345,12 @@ class Localplay
{
$data = $this->_player->get();
- if (!count($data) OR !is_array($data)) {
+ if (!count($data) or !is_array($data)) {
debug_event('localplay','Error Unable to get song info, check ' . $this->type . ' controller','1');
return array();
}
return $data;
-
} // get
/**
@@ -371,7 +365,9 @@ class Localplay
$value = int($value);
/* Make sure that it's between 0 and 100 */
- if ($value > 100 OR $value < 0) { return false; }
+ if ($value > 100 or $value < 0) {
+ return false;
+ }
if (!$this->_player->volume($value)) {
debug_event('localplay','Error: Unable to set volume, check ' . $this->type . ' controller','1');
@@ -379,7 +375,6 @@ class Localplay
}
return true;
-
} // volume_set
/**
@@ -395,7 +390,6 @@ class Localplay
}
return true;
-
} // volume_up
/**
@@ -411,7 +405,6 @@ class Localplay
}
return true;
-
} // volume_down
/**
@@ -427,7 +420,6 @@ class Localplay
}
return true;
-
} // volume_mute
/**
@@ -442,7 +434,6 @@ class Localplay
}
return true;
-
} // skip
/**
@@ -458,7 +449,6 @@ class Localplay
}
return true;
-
} // next
/**
@@ -474,7 +464,6 @@ class Localplay
}
return true;
-
} // prev
/**
@@ -490,7 +479,6 @@ class Localplay
}
return true;
-
} // pause
/**
@@ -502,7 +490,6 @@ class Localplay
$instances = $this->_player->get_instances();
return $instances;
-
} // get_instances
/**
@@ -514,7 +501,6 @@ class Localplay
$data = $this->_player->get_instance();
return $data['id'];
-
} // current_instance
/**
@@ -526,7 +512,6 @@ class Localplay
$data = $this->_player->get_instance($uid);
return $data;
-
} // get_instance
/**
@@ -538,7 +523,6 @@ class Localplay
$data = $this->_player->update_instance($uid,$data);
return $data;
-
} // update_instance
/**
@@ -548,7 +532,6 @@ class Localplay
public function add_instance($data)
{
$this->_player->add_instance($data);
-
} // add_instance
/**
@@ -558,7 +541,6 @@ class Localplay
public function delete_instance($instance_uid)
{
$this->_player->delete_instance($instance_uid);
-
} // delete_instance
/**
@@ -568,7 +550,6 @@ class Localplay
public function set_active_instance($instance)
{
$this->_player->set_active_instance($instance);
-
} // set_active_instance
/**
@@ -585,7 +566,6 @@ class Localplay
return true;
-
} // delete
/**
@@ -601,7 +581,6 @@ class Localplay
}
return true;
-
} // delete_all
/**
@@ -614,7 +593,6 @@ class Localplay
$fields = $this->_player->instance_fields();
return $fields;
-
} // get_instance_fields
/**
@@ -634,7 +612,6 @@ class Localplay
default:
return T_('Unknown');
} // switch on state
-
} // get_user_state
/**
@@ -657,8 +634,6 @@ class Localplay
$track_name = "[" . $status['track'] . "] - " . $track_name;
return $track_name;
-
} // get_user_playing
-
-
} // end localplay class
+
diff --git a/sources/lib/class/localplay_controller.abstract.php b/sources/lib/class/localplay_controller.abstract.php
index f7ecee9..e6d3d52 100644
--- a/sources/lib/class/localplay_controller.abstract.php
+++ b/sources/lib/class/localplay_controller.abstract.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -68,7 +68,6 @@ abstract class localplay_controller
$url = call_user_func(array($class,'play_url'),$object->id);
return $url;
-
} // get_url
/**
@@ -91,7 +90,7 @@ abstract class localplay_controller
{
// Define possible 'primary' keys
$primary_array = array('oid','demo_id','random');
- $data = array();
+ $data = array();
$variables = parse_url($url,PHP_URL_QUERY);
if ($variables) {
@@ -102,12 +101,10 @@ abstract class localplay_controller
$data['primary_key'] = $pkey;
return $data;
}
-
} // end foreach
}
return $data;
-
} // parse_url
-
} // end localplay_controller interface
+
diff --git a/sources/lib/class/mailer.class.php b/sources/lib/class/mailer.class.php
index c7ebb76..2921429 100644
--- a/sources/lib/class/mailer.class.php
+++ b/sources/lib/class/mailer.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -44,7 +44,6 @@ class Mailer
public function __construct()
{
// Eh bien.
-
} // Constructor
/**
@@ -80,7 +79,7 @@ class Mailer
$fromname = 'Ampache';
}
- $this->sender = $user . '@' . $domain;
+ $this->sender = $user . '@' . $domain;
$this->sender_name = $fromname;
} // set_default_sender
@@ -100,7 +99,7 @@ class Mailer
break ;
case 'inactive':
$inactive = time() - (30 * 86400);
- $sql = 'SELECT * FROM `user` WHERE `last_seen` <= ? AND `email` IS NOT NULL';
+ $sql = 'SELECT * FROM `user` WHERE `last_seen` <= ? AND `email` IS NOT NULL';
break;
case 'all':
default:
@@ -117,7 +116,6 @@ class Mailer
}
return $results;
-
} // get_users
/**
@@ -140,12 +138,12 @@ class Mailer
$mail = $phpmailer;
}
- $mail->CharSet = AmpConfig::get('site_charset');
+ $mail->CharSet = AmpConfig::get('site_charset');
$mail->Encoding = 'base64';
- $mail->From = $this->sender;
- $mail->Sender = $this->sender;
+ $mail->From = $this->sender;
+ $mail->Sender = $this->sender;
$mail->FromName = $this->sender_name;
- $mail->Subject = $this->subject;
+ $mail->Subject = $this->subject;
if (function_exists('mb_eregi_replace')) {
$this->message = mb_eregi_replace("\r\n", "\n", $this->message);
@@ -209,5 +207,5 @@ class Mailer
return $this->send($mail);
}
-
} // Mailer class
+
diff --git a/sources/lib/class/media.interface.php b/sources/lib/class/media.interface.php
index a65c36e..c85bf7c 100644
--- a/sources/lib/class/media.interface.php
+++ b/sources/lib/class/media.interface.php
@@ -2,21 +2,22 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
/**
@@ -61,5 +62,5 @@ interface media
public function get_stream_name();
public function set_played($user, $agent, $location);
-
} // end interface
+
diff --git a/sources/lib/class/memory_object.class.php b/sources/lib/class/memory_object.class.php
index 24c0628..6573fad 100644
--- a/sources/lib/class/memory_object.class.php
+++ b/sources/lib/class/memory_object.class.php
@@ -2,22 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; version 2
- * of the License.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -35,7 +34,6 @@ class memory_object
$this->_data[$key] = $value;
}
}
-
}
public function __set($name, $value)
diff --git a/sources/lib/class/movie.class.php b/sources/lib/class/movie.class.php
index 337bcfa..1cd50ec 100644
--- a/sources/lib/class/movie.class.php
+++ b/sources/lib/class/movie.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -45,7 +45,6 @@ class Movie extends Video
}
return true;
-
} // Constructor
/**
@@ -67,15 +66,14 @@ class Movie extends Video
public static function insert(array $data, $gtypes = array(), $options = array())
{
$trimmed = Catalog::trim_prefix(trim($data['original_name']));
- $name = $trimmed['string'];
- $prefix = $trimmed['prefix'];
+ $name = $trimmed['string'];
+ $prefix = $trimmed['prefix'];
$sql = "INSERT INTO `movie` (`id`, `original_name`, `prefix`, `summary`, `year`) " .
"VALUES (?, ?, ?, ?, ?)";
Dba::write($sql, array($data['id'], $name, $prefix, $data['summary'], $data['year']));
return $data['id'];
-
} // create
/**
@@ -88,25 +86,24 @@ class Movie extends Video
if (isset($data['original_name'])) {
$trimmed = Catalog::trim_prefix(trim($data['original_name']));
- $name = $trimmed['string'];
- $prefix = $trimmed['prefix'];
+ $name = $trimmed['string'];
+ $prefix = $trimmed['prefix'];
} else {
- $name = $this->original_name;
+ $name = $this->original_name;
$prefix = $this->prefix;
}
$summary = isset($data['summary']) ? $data['summary'] : $this->summary;
- $year = isset($data['year']) ? $data['summary'] : $this->year;
+ $year = Catalog::normalize_year(isset($data['year']) ? $data['year'] : $this->year);
$sql = "UPDATE `movie` SET `original_name` = ?, `prefix` = ?, `summary` = ?, `year` = ? WHERE `id` = ?";
Dba::write($sql, array($name, $prefix, $summary, $year, $this->id));
$this->original_name = $name;
- $this->prefix = $prefix;
- $this->summary = $summary;
- $this->year = $year;
+ $this->prefix = $prefix;
+ $this->summary = $summary;
+ $this->year = $year;
return $this->id;
-
} // update
/**
@@ -119,12 +116,11 @@ class Movie extends Video
parent::format($details);
$this->f_original_name = trim($this->prefix . " " . $this->f_title);
- $this->f_title = ($this->f_original_name ?: $this->f_title);
- $this->f_full_title = $this->f_title;
- $this->f_link = '' . $this->f_title . '';
+ $this->f_title = ($this->f_original_name ?: $this->f_title);
+ $this->f_full_title = $this->f_title;
+ $this->f_link = '' . $this->f_title . '';
return true;
-
} //format
/**
@@ -133,7 +129,7 @@ class Movie extends Video
*/
public function get_keywords()
{
- $keywords = parent::get_keywords();
+ $keywords = parent::get_keywords();
$keywords['type'] = array('important' => false,
'label' => null,
'value' => 'movie'
@@ -154,11 +150,11 @@ class Movie extends Video
{
$deleted = parent::remove_from_disk();
if ($deleted) {
- $sql = "DELETE FROM `movie` WHERE `id` = ?";
+ $sql = "DELETE FROM `movie` WHERE `id` = ?";
$deleted = Dba::write($sql, array($this->id));
}
return $deleted;
}
-
} // Movie class
+
diff --git a/sources/lib/class/openid.class.php b/sources/lib/class/openid.class.php
index 0ef49ff..c6a2189 100644
--- a/sources/lib/class/openid.class.php
+++ b/sources/lib/class/openid.class.php
@@ -2,27 +2,27 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
$openid_path = AmpConfig::get('prefix') . "/modules";
-$path = ini_get('include_path');
-$path = $openid_path . PATH_SEPARATOR . $path;
+$path = ini_get('include_path');
+$path = $openid_path . PATH_SEPARATOR . $path;
ini_set('include_path', $path);
require_once "Auth/OpenID/Consumer.php";
@@ -34,7 +34,7 @@ class Openid
{
public static function get_store()
{
- $store = null;
+ $store = null;
$store_path = AmpConfig::get('tmp_dir_path');
if (empty($store_path)) {
if (function_exists('sys_get_temp_dir')) {
@@ -68,7 +68,7 @@ class Openid
public static function get_consumer()
{
$consumer = null;
- $store = self::get_store();
+ $store = self::get_store();
if ($store) {
$consumer = new Auth_OpenID_Consumer($store);
}
@@ -83,7 +83,7 @@ class Openid
public static function get_policies()
{
$openid_required_pape = AmpConfig::get('openid_required_pape');
- $policies = array();
+ $policies = array();
if (!empty($openid_required_pape)) {
$papes = explode(',', $openid_required_pape);
foreach ($papes as $pape) {
@@ -93,5 +93,5 @@ class Openid
return $policies;
}
-
} // end of Openid class
+
diff --git a/sources/lib/class/personal_video.class.php b/sources/lib/class/personal_video.class.php
index 5471a1f..af58e19 100644
--- a/sources/lib/class/personal_video.class.php
+++ b/sources/lib/class/personal_video.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -43,7 +43,6 @@ class Personal_Video extends Video
}
return true;
-
} // Constructor
/**
@@ -69,7 +68,6 @@ class Personal_Video extends Video
Dba::write($sql, array($data['id'], $data['location'], $data['summary']));
return $data['id'];
-
} // create
/**
@@ -84,7 +82,6 @@ class Personal_Video extends Video
Dba::write($sql, array($data['location'], $data['summary'], $this->id));
return $this->id;
-
} // update
/**
@@ -99,7 +96,6 @@ class Personal_Video extends Video
$this->f_location = $this->location;
return true;
-
} //format
/**
@@ -109,11 +105,11 @@ class Personal_Video extends Video
{
$deleted = parent::remove_from_disk();
if ($deleted) {
- $sql = "DELETE FROM `personal_video` WHERE `id` = ?";
+ $sql = "DELETE FROM `personal_video` WHERE `id` = ?";
$deleted = Dba::write($sql, array($this->id));
}
return $deleted;
}
-
} // Personal_Video class
+
diff --git a/sources/lib/class/playable_item.interface.php b/sources/lib/class/playable_item.interface.php
index 7b51343..3d54499 100644
--- a/sources/lib/class/playable_item.interface.php
+++ b/sources/lib/class/playable_item.interface.php
@@ -2,21 +2,22 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
/**
@@ -77,5 +78,5 @@ interface playable_item
* @return int[]
*/
public function get_catalogs();
-
} // end interface
+
diff --git a/sources/lib/class/playlist.class.php b/sources/lib/class/playlist.class.php
index 475a597..f4b8acd 100644
--- a/sources/lib/class/playlist.class.php
+++ b/sources/lib/class/playlist.class.php
@@ -2,22 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; version 2
- * of the License.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -51,7 +50,6 @@ class Playlist extends playlist_object
foreach ($info as $key=>$value) {
$this->$key = $value;
}
-
} // Playlist
/**
@@ -73,17 +71,18 @@ class Playlist extends playlist_object
*/
public static function build_cache($ids)
{
- if (!count($ids)) { return false; }
+ if (!count($ids)) {
+ return false;
+ }
$idlist = '(' . implode(',',$ids) . ')';
- $sql = "SELECT * FROM `playlist` WHERE `id` IN $idlist";
+ $sql = "SELECT * FROM `playlist` WHERE `id` IN $idlist";
$db_results = Dba::read($sql);
while ($row = Dba::fetch_assoc($db_results)) {
parent::add_to_cache('playlist',$row['id'],$row);
}
-
} // build_cache
/**
@@ -96,15 +95,25 @@ class Playlist extends playlist_object
$user_id = $GLOBALS['user']->id;
}
- $sql = 'SELECT `id` FROM `playlist`' .
- ' WHERE `user` = ?';
+ $sql = 'SELECT `id` FROM `playlist`';
+ $params = array();
+ if ($user_id > -1) {
+ $sql .= ' WHERE `user` = ?';
+ $params[] = $user_id;
+ }
+
if ($incl_public) {
- $sql .= " OR `type` = 'public'";
+ if (count($params) > 0) {
+ $sql .= ' OR ';
+ } else {
+ $sql .= ' WHERE ';
+ }
+ $sql .= "`type` = 'public'";
}
$sql .= ' ORDER BY `name`';
- $db_results = Dba::read($sql, array($user_id));
- $results = array();
+ $db_results = Dba::read($sql, $params);
+ $results = array();
while ($row = Dba::fetch_assoc($db_results)) {
$results[] = $row['id'];
}
@@ -120,9 +129,8 @@ class Playlist extends playlist_object
public function format($details = true)
{
parent::format($details);
- $this->link = AmpConfig::get('web_path') . '/playlist.php?action=show_playlist&playlist_id=' . $this->id;
+ $this->link = AmpConfig::get('web_path') . '/playlist.php?action=show_playlist&playlist_id=' . $this->id;
$this->f_link = '' . $this->f_name . '';
-
} // format
/**
@@ -132,13 +140,12 @@ class Playlist extends playlist_object
*/
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, $this->id));
$row = Dba::fetch_assoc($db_results);
return $row;
-
} // get_track
/**
@@ -151,7 +158,7 @@ class Playlist extends playlist_object
{
$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`";
$db_results = Dba::read($sql, array($this->id));
while ($row = Dba::fetch_assoc($db_results)) {
@@ -164,7 +171,6 @@ class Playlist extends playlist_object
} // end while
return $results;
-
} // get_items
/**
@@ -182,7 +188,6 @@ class Playlist extends playlist_object
$db_results = Dba::read($sql, array($this->id));
while ($row = Dba::fetch_assoc($db_results)) {
-
$results[] = array(
'object_type' => $row['object_type'],
'object_id' => $row['object_id']
@@ -190,7 +195,6 @@ class Playlist extends playlist_object
} // end while
return $results;
-
} // get_random_items
/**
@@ -202,7 +206,7 @@ class Playlist extends playlist_object
{
$results = array();
- $sql = "SELECT * FROM `playlist_data` WHERE `playlist` = ? AND `object_type` = 'song' ORDER BY `track`";
+ $sql = "SELECT * FROM `playlist_data` WHERE `playlist` = ? AND `object_type` = 'song' ORDER BY `track`";
$db_results = Dba::read($sql, array($this->id));
while ($r = Dba::fetch_assoc($db_results)) {
@@ -210,24 +214,27 @@ class Playlist extends playlist_object
} // end while
return $results;
-
} // get_songs
/**
- * get_song_count
- * 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
+ * get_media_count
+ * This simply returns a int of how many media elements exist in this playlist
+ * For now let's consider a dyn_media a single entry
*/
- public function get_song_count()
+ public function get_media_count($type = '')
{
- $sql = "SELECT COUNT(`id`) FROM `playlist_data` WHERE `playlist` = ?";
- $db_results = Dba::read($sql, array($this->id));
+ $params = array($this->id);
+ $sql = "SELECT COUNT(`id`) FROM `playlist_data` WHERE `playlist` = ?";
+ if (!empty($type)) {
+ $sql .= " AND `object_type` = ?";
+ $params[] = $type;
+ }
+ $db_results = Dba::read($sql, $params);
$results = Dba::fetch_row($db_results);
return $results['0'];
-
- } // get_song_count
+ } // get_media_count
/**
* get_total_duration
@@ -235,16 +242,15 @@ class Playlist extends playlist_object
*/
public function get_total_duration()
{
- $songs = self::get_songs();
+ $songs = self::get_songs();
$idlist = '(' . implode(',', $songs) . ')';
- $sql = "SELECT SUM(`time`) FROM `song` WHERE `id` IN $idlist";
+ $sql = "SELECT SUM(`time`) FROM `song` WHERE `id` IN $idlist";
$db_results = Dba::read($sql);
$results = Dba::fetch_row($db_results);
return $results['0'];
-
} // get_total_duration
/**
@@ -256,7 +262,7 @@ class Playlist extends playlist_object
{
$results = array();
- $sql = "SELECT `id` FROM `playlist` WHERE `user` = ? ORDER BY `name`";
+ $sql = "SELECT `id` FROM `playlist` WHERE `user` = ? ORDER BY `name`";
$db_results = Dba::read($sql, array($user_id));
while ($row = Dba::fetch_assoc($db_results)) {
@@ -264,7 +270,6 @@ class Playlist extends playlist_object
}
return $results;
-
} // get_users
/**
@@ -292,7 +297,6 @@ class Playlist extends playlist_object
if ($this->_update_item('type',$new_type,50)) {
$this->type = $new_type;
}
-
} // update_type
/**
@@ -304,7 +308,6 @@ class Playlist extends playlist_object
if ($this->_update_item('name',$new_name,50)) {
$this->name = $new_name;
}
-
} // update_name
/**
@@ -313,15 +316,14 @@ class Playlist extends playlist_object
*/
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;
}
- $sql = "UPDATE `playlist` SET `$field` = ? WHERE `id` = ?";
+ $sql = "UPDATE `playlist` SET `$field` = ? WHERE `id` = ?";
$db_results = Dba::write($sql, array($value, $this->id));
return $db_results;
-
} // update_item
/**
@@ -332,7 +334,6 @@ class Playlist extends playlist_object
{
$sql = "UPDATE `playlist_data` SET `track` = ? WHERE `id` = ?";
Dba::write($sql, array($index, $track_id));
-
} // update_track_number
/**
@@ -362,7 +363,6 @@ class Playlist extends playlist_object
);
}
$this->add_medias($medias, $ordered);
-
} // add_songs
public function add_medias($medias, $ordered=false)
@@ -371,11 +371,11 @@ class Playlist extends playlist_object
* append, rather then integrate take end track # and add it to
* $song->track add one to make sure it really is 'next'
*/
- $sql = "SELECT `track` FROM `playlist_data` WHERE `playlist` = ? ORDER BY `track` DESC LIMIT 1";
+ $sql = "SELECT `track` FROM `playlist_data` WHERE `playlist` = ? ORDER BY `track` DESC LIMIT 1";
$db_results = Dba::read($sql, array($this->id));
- $data = Dba::fetch_assoc($db_results);
- $base_track = $data['track'];
- debug_event('add_medias', 'Track number: '.$base_track, '5');
+ $data = Dba::fetch_assoc($db_results);
+ $base_track = $data['track'] ?: 0;
+ debug_event('add_medias', 'Track number: ' . $base_track, '5');
$i = 0;
foreach ($medias as $data) {
@@ -395,7 +395,6 @@ class Playlist extends playlist_object
" VALUES (?, ?, ?, ?)";
Dba::write($sql, array($this->id, $data['object_id'], $data['object_type'], $track));
} // if valid id
-
} // end foreach medias
}
@@ -417,7 +416,6 @@ class Playlist extends playlist_object
$insert_id = Dba::insert_id();
return $insert_id;
-
} // create
/**
@@ -427,7 +425,6 @@ class Playlist extends playlist_object
public function set_items()
{
$this->items = $this->get_items();
-
} // set_items
/**
@@ -440,7 +437,6 @@ class Playlist extends playlist_object
Dba::write($sql, array($this->id, $id));
return true;
-
} // delete_track
/**
@@ -453,7 +449,6 @@ class Playlist extends playlist_object
Dba::write($sql, array($this->id, $track));
return true;
-
} // delete_track_number
/**
@@ -472,7 +467,6 @@ class Playlist extends playlist_object
Dba::write($sql, array($this->id));
return true;
-
} // delete
/**
@@ -494,14 +488,14 @@ class Playlist extends playlist_object
B.`track` ASC";
$db_results = Dba::query($sql, array($this->id));
- $i = 1;
+ $i = 1;
$results = array();
while ($r = Dba::fetch_assoc($db_results)) {
- $new_data = array();
+ $new_data = array();
$new_data['id'] = $r['id'];
$new_data['track'] = $i;
- $results[] = $new_data;
+ $results[] = $new_data;
$i++;
} // end while results
@@ -511,7 +505,6 @@ class Playlist extends playlist_object
} // foreach re-ordered results
return true;
-
} // sort_tracks
-
} // class Playlist
+
diff --git a/sources/lib/class/playlist_object.abstract.php b/sources/lib/class/playlist_object.abstract.php
index 75bd7ba..168e954 100644
--- a/sources/lib/class/playlist_object.abstract.php
+++ b/sources/lib/class/playlist_object.abstract.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -74,7 +74,6 @@ abstract class playlist_object extends database_object implements library_item
$client->format();
$this->f_user = $client->f_name;
}
-
} // format
/**
@@ -92,7 +91,6 @@ abstract class playlist_object extends database_object implements library_item
} else {
return Access::check('interface', 75);
}
-
} // has_access
public function get_medias($filter_type = null)
@@ -128,7 +126,7 @@ abstract class playlist_object extends database_object implements library_item
public function get_childrens()
{
$childrens = array();
- $items = $this->get_items();
+ $items = $this->get_items();
foreach ($items as $item) {
if (!in_array($item['object_type'], $childrens)) {
$childrens[$item['object_type']] = array();
@@ -174,5 +172,5 @@ abstract class playlist_object extends database_object implements library_item
{
return array();
}
-
} // end playlist_object
+
diff --git a/sources/lib/class/plex_api.class.php b/sources/lib/class/plex_api.class.php
index d232e26..920c8de 100644
--- a/sources/lib/class/plex_api.class.php
+++ b/sources/lib/class/plex_api.class.php
@@ -2,22 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; version 2
- * of the License.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -41,11 +40,11 @@ class Plex_Api
protected static function is_local()
{
- $local = false;
+ $local = false;
$local_auth = AmpConfig::get('plex_local_auth');
if (!$local_auth) {
- $ip = $_SERVER['REMOTE_ADDR'];
- $lip = ip2long($ip);
+ $ip = $_SERVER['REMOTE_ADDR'];
+ $lip = ip2long($ip);
$rangs = array(
array('127.0.0.1', '127.0.0.1'),
array('10.0.0.1', '10.255.255.254'),
@@ -71,7 +70,7 @@ class Plex_Api
{
$isLocal = self::is_local();
- $headers = apache_request_headers();
+ $headers = apache_request_headers();
$myplex_token = $headers['X-Plex-Token'];
if (empty($myplex_token)) {
$myplex_token = $_REQUEST['X-Plex-Token'];
@@ -96,12 +95,12 @@ class Plex_Api
$createSession = false;
Session::gc();
$username = "";
- $email = trim(Session::read((string) $myplex_token));
+ $email = trim(Session::read((string) $myplex_token));
if (empty($email)) {
$createSession = true;
- $xml = self::get_server_authtokens();
- $validToken = false;
+ $xml = self::get_server_authtokens();
+ $validToken = false;
foreach ($xml->access_token as $tk) {
if ((string) $tk['token'] == $myplex_token) {
$username = (string) $tk['username'];
@@ -155,7 +154,7 @@ class Plex_Api
}
}
} else {
- $email = $username;
+ $email = $username;
$username = null;
$GLOBALS['user'] = new User();
@@ -177,8 +176,8 @@ class Plex_Api
if (!$sid) {
$sid = $myplex_token;
if ($sid) {
- session_id($sid);
- Session::create_cookie();
+ session_id($sid);
+ Session::create_cookie();
}
}
if (!empty($sid) && Session::exists('api', $sid)) {
@@ -186,7 +185,7 @@ class Plex_Api
$GLOBALS['user'] = User::get_from_username($_SESSION['userdata']['username']);
} else {
$GLOBALS['user'] = new User();
- $data = array(
+ $data = array(
'type' => 'api',
'sid' => $sid,
);
@@ -244,8 +243,8 @@ class Plex_Api
$ach = $reqheaders['Access-Control-Request-Headers'];
if ($ach) {
//$filter = explode(',', $ach);
- $filter = null;
- $headers = self::getPlexHeaders(true, $filter);
+ $filter = null;
+ $headers = self::getPlexHeaders(true, $filter);
$headerkeys = array();
foreach ($headers as $key => $value) {
$headerkeys[] = $key;
@@ -300,7 +299,7 @@ class Plex_Api
break;
}
header("Content-type: text/html", true);
- header("HTTP/1.0 ". $code . " " . $error, true, $code);
+ header("HTTP/1.0 " . $code . " " . $error, true, $code);
$html = "" . $error . "
" . $code . " " . $error . "
";
self::apiOutput($html);
@@ -319,7 +318,8 @@ class Plex_Api
);
$action = 'users/sign_in.xml';
- $res = self::myPlexRequest($action, $options, $headers);;
+ $res = self::myPlexRequest($action, $options, $headers);
+ ;
return $res['xml']['authenticationToken'];
}
@@ -352,8 +352,8 @@ class Plex_Api
public static function publishDeviceConnection($authtoken)
{
- $headers = array ();
- $action = 'devices/' . Plex_XML_Data::getMachineIdentifier() . '?Connection[][uri]=' . Plex_XML_Data::getServerUri() . '&X-Plex-Token=' . $authtoken;
+ $headers = array ();
+ $action = 'devices/' . Plex_XML_Data::getMachineIdentifier() . '?Connection[][uri]=' . Plex_XML_Data::getServerUri() . '&X-Plex-Token=' . $authtoken;
$curlopts = array(
CURLOPT_CUSTOMREQUEST => "PUT"
);
@@ -366,7 +366,7 @@ class Plex_Api
$headers = array (
'Content-Type: text/xml'
);
- $action = 'servers/' . Plex_XML_Data::getMachineIdentifier() . '.xml?auth_token=' . $authtoken;
+ $action = 'servers/' . Plex_XML_Data::getMachineIdentifier() . '.xml?auth_token=' . $authtoken;
$curlopts = array(
CURLOPT_CUSTOMREQUEST => "DELETE"
);
@@ -437,7 +437,7 @@ class Plex_Api
public static function replay_header($ch, $header)
{
$rheader = trim($header);
- $rhpart = explode(':', $rheader);
+ $rhpart = explode(':', $rheader);
if (!empty($rheader) && count($rhpart) > 1) {
if ($rhpart[0] != "Transfer-Encoding") {
header($rheader);
@@ -462,7 +462,7 @@ class Plex_Api
protected static function myPlexRequest($action, $curlopts = array(), $headers = array(), $proxy = false)
{
- $server = Plex_XML_Data::getServerUri();
+ $server = Plex_XML_Data::getServerUri();
$allheaders = array();
if (!$proxy) {
$allheadersarr = self::getPlexHeaders();
@@ -495,12 +495,12 @@ class Plex_Api
$ch = curl_init($url);
curl_setopt_array($ch, $options);
- $r = curl_exec($ch);
- $res = array();
+ $r = curl_exec($ch);
+ $res = array();
$res['status'] = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$res['headers'] = self::$request_headers;
- $res['raw'] = $r;
+ $res['raw'] = $r;
try {
$res['xml'] = simplexml_load_string($r);
} catch (Exception $e) {
@@ -558,10 +558,9 @@ class Plex_Api
{
if (count($params) == 2) {
if ($params[0] == ':' && $params[1] == 'transcode') {
-
- $width = $_REQUEST['width'];
+ $width = $_REQUEST['width'];
$height = $_REQUEST['height'];
- $url = $_REQUEST['url'];
+ $url = $_REQUEST['url'];
// Replace 32400 request port with the real listening port
// *** To `Plex Inc`: ***
@@ -573,7 +572,7 @@ class Plex_Api
$options = Core::requests_options();
if (strpos($url, $localrs) !== false) {
$options = array(); // In case proxy is set, no proxy for local addresses
- $url = "http://127.0.0.1:" . Plex_XML_Data::getServerPort() . "/" . substr($url, strlen($localrs));
+ $url = "http://127.0.0.1:" . Plex_XML_Data::getServerPort() . "/" . substr($url, strlen($localrs));
}
if ($width && $height && $url) {
@@ -582,9 +581,9 @@ class Plex_Api
ob_clean();
$mime = $request->headers['content-type'];
self::setHeader($mime);
- $art = new Art(0);
+ $art = new Art(0);
$art->raw = $request->body;
- $thumb = $art->generate_thumb($art->raw, array('width' => $width, 'height' => $height), $mime);
+ $thumb = $art->generate_thumb($art->raw, array('width' => $width, 'height' => $height), $mime);
echo $thumb['thumb'];
exit();
}
@@ -599,14 +598,14 @@ class Plex_Api
if ($params[0] == ':' && $params[1] == 'transcode') {
if (count($params) == 3) {
$format = $_REQUEST['format'] ?: pathinfo($params[2], PATHINFO_EXTENSION);
- $url = $_REQUEST['url'];
- $br = $_REQUEST['audioBitrate'];
+ $url = $_REQUEST['url'];
+ $br = $_REQUEST['audioBitrate'];
if (preg_match("/\/parts\/([0-9]+)\//", $url, $matches)) {
$song_id = Plex_XML_Data::getAmpacheId($matches[1]);
}
} elseif (count($params) == 4 && $params[2] == 'universal') {
$format = pathinfo($params[3], PATHINFO_EXTENSION);
- $path = $_REQUEST['path'];
+ $path = $_REQUEST['path'];
// Should be the maximal allowed bitrate, not necessary the bitrate used but Ampache doesn't support this kind of option yet
$br = $_REQUEST['maxAudioBitrate'];
if (preg_match("/\/metadata\/([0-9]+)/", $path, $matches)) {
@@ -645,19 +644,19 @@ class Plex_Api
$n = count($params);
if ($n == 2) {
$transcode_to = $params[0];
- $action = $params[1];
- $id = '';
+ $action = $params[1];
+ $id = '';
- $path = $_GET['path'];
+ $path = $_GET['path'];
$protocol = $_GET['protocol'];
- $offset = $_GET['offset'];
+ $offset = $_GET['offset'];
// Transcode arguments.
- $videoQuality = $_GET['videoQuality'];
+ $videoQuality = $_GET['videoQuality'];
$videoResolution = $_GET['videoResolution'];
$maxVideoBitrate = $_GET['maxVideoBitrate'];
- $subtitleSize = $_GET['subtitleSize'];
- $audioBoost = $_GET['audioBoost'];
+ $subtitleSize = $_GET['subtitleSize'];
+ $audioBoost = $_GET['audioBoost'];
$additional_params = '&vsettings=';
if ($videoResolution) {
@@ -684,7 +683,7 @@ class Plex_Api
//$directStream = $_GET['directStream'];
$uriroot = '/library/metadata/';
- $upos = strrpos($path, $uriroot);
+ $upos = strrpos($path, $uriroot);
if ($upos !== false) {
$id = substr($path, $upos + strlen($uriroot));
}
@@ -698,15 +697,18 @@ class Plex_Api
$videoResolution = $_GET['videoResolution'];
$maxVideoBitrate = $_GET['maxVideoBitrate'];
- if (!$maxVideoBitrate)
+ if (!$maxVideoBitrate) {
$maxVideoBitrate = 8175;
+ }
echo "#EXTM3U\n";
echo "#EXT-X-STREAM-INF:PROGRAM-ID=1";
- if ($maxVideoBitrate)
+ if ($maxVideoBitrate) {
echo ",BANDWIDTH=" . ($maxVideoBitrate * 1000);
- if ($videoResolution)
+ }
+ if ($videoResolution) {
echo ",RESOLUTION=" . $videoResolution;
+ }
echo "\n";
echo "hls.m3u8?" . substr($_SERVER['QUERY_STRING'], strpos($_SERVER['QUERY_STRING'], '&') + 1);
} elseif ($protocol == "http") {
@@ -771,7 +773,7 @@ class Plex_Api
if ($n == 0) {
Plex_XML_Data::setSections($r, Catalog::get_catalogs());
} else {
- $key = $params[0];
+ $key = $params[0];
$catalog = Catalog::create_from_id($key);
if (!$catalog) {
self::createError(404);
@@ -779,7 +781,7 @@ class Plex_Api
if ($n == 1) {
Plex_XML_Data::setSectionContent($r, $catalog);
} elseif ($n == 2) {
- $view = $params[1];
+ $view = $params[1];
$gtypes = $catalog->get_gather_types();
if ($gtypes[0] == 'music') {
$type = 'artist';
@@ -849,12 +851,12 @@ class Plex_Api
public static function library_metadata($params)
{
- $r = Plex_XML_Data::createLibContainer();
- $n = count($params);
+ $r = Plex_XML_Data::createLibContainer();
+ $n = count($params);
$litem = null;
$createMode = ($_SERVER['REQUEST_METHOD'] == 'POST');
- $editMode = ($_SERVER['REQUEST_METHOD'] == 'PUT');
+ $editMode = ($_SERVER['REQUEST_METHOD'] == 'PUT');
if ($n > 0) {
$key = $params[0];
@@ -867,7 +869,7 @@ class Plex_Api
if ($n == 1) {
// Should we check that files still exists here?
$checkFiles = $_REQUEST['checkFiles'];
- $extra = $_REQUEST['includeExtra'];
+ $extra = $_REQUEST['includeExtra'];
if (Plex_XML_Data::isArtist($key)) {
$litem = new Artist($id);
@@ -949,7 +951,6 @@ class Plex_Api
}
Plex_XML_Data::addPlaylist($r, $litem);
}
-
} else {
$subact = $params[1];
if ($subact == "children") {
@@ -957,18 +958,24 @@ class Plex_Api
$litem = new Artist($id);
$litem->format();
Plex_XML_Data::setArtistRoot($r, $litem);
- } else if (Plex_XML_Data::isAlbum($key)) {
- $litem = new Album($id);
- $litem->format();
- Plex_XML_Data::setAlbumRoot($r, $litem);
- } else if (Plex_XML_Data::isTVShow($key)) {
- $litem = new TVShow($id);
- $litem->format();
- Plex_XML_Data::setTVShowRoot($r, $litem);
- } else if (Plex_XML_Data::isTVShowSeason($key)) {
- $litem = new TVShow_Season($id);
- $litem->format();
- Plex_XML_Data::setTVShowSeasonRoot($r, $litem);
+ } else {
+ if (Plex_XML_Data::isAlbum($key)) {
+ $litem = new Album($id);
+ $litem->format();
+ Plex_XML_Data::setAlbumRoot($r, $litem);
+ } else {
+ if (Plex_XML_Data::isTVShow($key)) {
+ $litem = new TVShow($id);
+ $litem->format();
+ Plex_XML_Data::setTVShowRoot($r, $litem);
+ } else {
+ if (Plex_XML_Data::isTVShowSeason($key)) {
+ $litem = new TVShow_Season($id);
+ $litem->format();
+ Plex_XML_Data::setTVShowSeasonRoot($r, $litem);
+ }
+ }
+ }
}
} elseif ($subact == "thumbs" || $subact == "posters" || $subact == "arts" || $subact == 'backgrounds') {
$kind = Plex_XML_Data::getPhotoKind($subact);
@@ -1000,16 +1007,26 @@ class Plex_Api
$art = null;
if (Plex_XML_Data::isArtist($key)) {
$art = new Art($id, "artist", $kind);
- } else if (Plex_XML_Data::isAlbum($key)) {
- $art = new Art($id, "album", $kind);
- } else if (Plex_XML_Data::isTrack($key)) {
- $art = new Art($id, "song", $kind);
- } else if (Plex_XML_Data::isTVShow($key)) {
- $art = new Art($id, "tvshow", $kind);
- } else if (Plex_XML_Data::isTVShowSeason($key)) {
- $art = new Art($id, "tvshow_season", $kind);
- } else if (Plex_XML_Data::isVideo($key)) {
- $art = new Art($id, "video", $kind);
+ } else {
+ if (Plex_XML_Data::isAlbum($key)) {
+ $art = new Art($id, "album", $kind);
+ } else {
+ if (Plex_XML_Data::isTrack($key)) {
+ $art = new Art($id, "song", $kind);
+ } else {
+ if (Plex_XML_Data::isTVShow($key)) {
+ $art = new Art($id, "tvshow", $kind);
+ } else {
+ if (Plex_XML_Data::isTVShowSeason($key)) {
+ $art = new Art($id, "tvshow_season", $kind);
+ } else {
+ if (Plex_XML_Data::isVideo($key)) {
+ $art = new Art($id, "video", $kind);
+ }
+ }
+ }
+ }
+ }
}
if ($art != null) {
@@ -1020,10 +1037,10 @@ class Plex_Api
self::setHeader($art->raw_mime);
echo $art->raw;
} else {
- $dim = array();
- $dim['width'] = $size;
+ $dim = array();
+ $dim['width'] = $size;
$dim['height'] = $size;
- $thumb = $art->get_thumb($dim);
+ $thumb = $art->get_thumb($dim);
self::setHeader($art->thumb_mime);
echo $thumb['thumb'];
}
@@ -1052,7 +1069,7 @@ class Plex_Api
set_time_limit(0);
ob_end_clean();
- $headers = apache_request_headers();
+ $headers = apache_request_headers();
$reqheaders = array();
if (isset($headers['Range'])) {
$reqheaders[] = "Range: " . $headers['Range'];
@@ -1071,9 +1088,9 @@ class Plex_Api
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_TIMEOUT => 0
));
- if (curl_exec($ch) === false) {
+ if (curl_exec($ch) === false) {
debug_event('plex-api', 'Curl error: ' . curl_error($ch),1);
- }
+ }
curl_close($ch);
}
@@ -1107,7 +1124,7 @@ class Plex_Api
} elseif ($n == 1) {
if ($_SERVER['REQUEST_METHOD'] == 'PUT') {
if (isset($_GET['subtitleStreamID'])) {
- $lang_code = dechex(hex2bin(substr($_GET['subtitleStreamID'], 0, 2)));
+ $lang_code = dechex(hex2bin(substr($_GET['subtitleStreamID'], 0, 2)));
$_SESSION['iframe']['subtitle'] = $lang_code;
}
}
@@ -1117,9 +1134,9 @@ class Plex_Api
public static function library_recentlyadded($params)
{
- $data = array();
+ $data = array();
$data['album'] = Stats::get_newest('album', 25);
- $r = Plex_XML_Data::createLibContainer();
+ $r = Plex_XML_Data::createLibContainer();
Plex_XML_Data::setCustomView($r, $data);
Plex_XML_Data::setContainerSize($r);
self::apiOutputXml($r->asXML());
@@ -1127,9 +1144,9 @@ class Plex_Api
public static function library_ondeck($params)
{
- $data = array();
+ $data = array();
$data['album'] = Stats::get_recent('album', 25);
- $r = Plex_XML_Data::createLibContainer();
+ $r = Plex_XML_Data::createLibContainer();
Plex_XML_Data::setCustomView($r, $data);
Plex_XML_Data::setContainerSize($r);
self::apiOutputXml($r->asXML());
@@ -1161,11 +1178,11 @@ class Plex_Api
public static function system_agents($params)
{
- $r = Plex_XML_Data::createSysContainer();
+ $r = Plex_XML_Data::createSysContainer();
$addcontributors = false;
- $mediaType = $_REQUEST['mediaType'];
+ $mediaType = $_REQUEST['mediaType'];
if (count($params) >= 3 && $params[1] == 'config') {
- $mediaType = $params[2];
+ $mediaType = $params[2];
$addcontributors = true;
}
@@ -1202,7 +1219,7 @@ class Plex_Api
public static function system_agents_contributors($params)
{
- $mediaType = $_REQUEST['mediaType'];
+ $mediaType = $_REQUEST['mediaType'];
$primaryAgent = $_REQUEST['primaryAgent'];
$r = Plex_XML_Data::createSysContainer();
@@ -1222,7 +1239,7 @@ class Plex_Api
{
if (count($params) > 0) {
$type = $params[0];
- $r = Plex_XML_Data::createSysContainer();
+ $r = Plex_XML_Data::createSysContainer();
Plex_XML_Data::setScanners($r, $type);
Plex_XML_Data::setContainerSize($r);
self::apiOutputXml($r->asXML());
@@ -1245,7 +1262,9 @@ class Plex_Api
$userid = $params[0];
}
// Not supported yet
- if ($userid > 1) { self::createError(404); }
+ if ($userid > 1) {
+ self::createError(404);
+ }
$r = Plex_XML_Data::createAccountContainer();
Plex_XML_Data::setAccounts($r, $userid);
@@ -1316,10 +1335,10 @@ class Plex_Api
public static function timeline($params)
{
$ratingKey = $_REQUEST['ratingKey'];
- $key = $_REQUEST['key'];
- $state = $_REQUEST['state'];
- $time = $_REQUEST['time'];
- $duration = $_REQUEST['duration'];
+ $key = $_REQUEST['key'];
+ $state = $_REQUEST['state'];
+ $time = $_REQUEST['time'];
+ $duration = $_REQUEST['duration'];
// Not supported right now (maybe in a future for broadcast?)
header('Content-Type: text/html');
@@ -1327,9 +1346,9 @@ class Plex_Api
public static function rate($params)
{
- $id = $_REQUEST['key'];
+ $id = $_REQUEST['key'];
$identifier = $_REQUEST['identifier'];
- $rating = $_REQUEST['rating'];
+ $rating = $_REQUEST['rating'];
if ($identifier == 'com.plexapp.plugins.library') {
$robj = new Rating(Plex_XML_Data::getAmpacheId($id), Plex_XML_Data::getLibraryItemType($id));
@@ -1344,7 +1363,7 @@ class Plex_Api
}
$action = 'users/account?auth_token=' . $authtoken;
- $res = self::myPlexRequest($action);
+ $res = self::myPlexRequest($action);
return $res['xml'];
}
@@ -1363,8 +1382,8 @@ class Plex_Api
{
if ($params[0] == 'sign_in.xml') {
$curlopts = array();
- $headers = array();
- $res = self::myPlexRequest('users/sign_in.xml', $curlopts, $headers, true);
+ $headers = array();
+ $res = self::myPlexRequest('users/sign_in.xml', $curlopts, $headers, true);
foreach ($res['headers'] as $header) {
header($header);
@@ -1373,7 +1392,9 @@ class Plex_Api
if ($res['status'] == '201') {
Plex_XML_Data::setMyPlexSubscription($res['xml']);
self::apiOutput($res['xml']->asXML());
- } else { self::createError($res['status']); }
+ } else {
+ self::createError($res['status']);
+ }
}
}
@@ -1391,8 +1412,8 @@ class Plex_Api
$n = count($params);
$createMode = ($_SERVER['REQUEST_METHOD'] == 'POST');
- $editMode = ($_SERVER['REQUEST_METHOD'] == 'PUT');
- $delMode = ($_SERVER['REQUEST_METHOD'] == 'DELETE');
+ $editMode = ($_SERVER['REQUEST_METHOD'] == 'PUT');
+ $delMode = ($_SERVER['REQUEST_METHOD'] == 'DELETE');
if ($createMode || $editMode || $delMode) {
self::check_access(50);
}
@@ -1407,12 +1428,12 @@ class Plex_Api
//$summary = $_GET['summary'];
$uri = $_GET['uri'];
- $plid = Playlist::create($title, 'public');
+ $plid = Playlist::create($title, 'public');
$playlist = new Playlist($plid);
- $key = Plex_XML_Data::getKeyFromFullUri($uri);
- $id = Plex_XML_Data::getKeyFromMetadataUri($key);
+ $key = Plex_XML_Data::getKeyFromFullUri($uri);
+ $id = Plex_XML_Data::getKeyFromMetadataUri($key);
if ($id) {
- $item = Plex_XML_Data::createLibraryItem($id);
+ $item = Plex_XML_Data::createLibraryItem($id);
$medias = $item->get_medias();
$playlist->add_medias($medias);
}
@@ -1450,9 +1471,9 @@ class Plex_Api
// Add a new item to playlist
$uri = $_GET['uri'];
$key = Plex_XML_Data::getKeyFromFullUri($uri);
- $id = Plex_XML_Data::getKeyFromMetadataUri($key);
+ $id = Plex_XML_Data::getKeyFromMetadataUri($key);
if ($id) {
- $item = Plex_XML_Data::createLibraryItem($id);
+ $item = Plex_XML_Data::createLibraryItem($id);
$medias = $item->get_medias();
$playlist->add_medias($medias);
Plex_XML_Data::addPlaylist($r, $playlist);
@@ -1485,11 +1506,11 @@ class Plex_Api
$playlistID = $params[0];
Plex_XML_Data::setTmpPlayQueue($r, $playlistID);
} else {
- $type = $_GET['type'];
+ $type = $_GET['type'];
$playlistID = $_GET['playlistID'];
- $uri = $_GET['uri'];
- $key = $_GET['key'];
- $shuffle = $_GET['shuffle'];
+ $uri = $_GET['uri'];
+ $key = $_GET['key'];
+ $shuffle = $_GET['shuffle'];
Plex_XML_Data::setPlayQueue($r, $type, $playlistID, $uri, $key, $shuffle);
}
diff --git a/sources/lib/class/plex_xml_data.class.php b/sources/lib/class/plex_xml_data.class.php
index 9dae707..6b555b9 100644
--- a/sources/lib/class/plex_xml_data.class.php
+++ b/sources/lib/class/plex_xml_data.class.php
@@ -2,22 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; version 2
- * of the License.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -31,22 +30,22 @@
class Plex_XML_Data
{
// 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 = 10000000;
- const AMPACHEID_ALBUM = 20000000;
- const AMPACHEID_TRACK = 30000000;
- const AMPACHEID_SONG = 40000000;
- const AMPACHEID_TVSHOW = 50000000;
+ const AMPACHEID_ARTIST = 10000000;
+ const AMPACHEID_ALBUM = 20000000;
+ const AMPACHEID_TRACK = 30000000;
+ const AMPACHEID_SONG = 40000000;
+ const AMPACHEID_TVSHOW = 50000000;
const AMPACHEID_TVSHOW_SEASON = 60000000;
- const AMPACHEID_VIDEO = 70000000;
- const AMPACHEID_PLAYLIST = 80000000;
- const AMPACHEID_PART = 100000000;
+ const AMPACHEID_VIDEO = 70000000;
+ const AMPACHEID_PLAYLIST = 80000000;
+ const AMPACHEID_PART = 100000000;
- const PLEX_ARTIST = 8;
- const PLEX_ALBUM = 9;
- const PLEX_TVSHOW = 2;
- const PLEX_SEASON = 3;
- const PLEX_EPISODE = 4;
- const PLEX_MOVIE = 1;
+ const PLEX_ARTIST = 8;
+ const PLEX_ALBUM = 9;
+ const PLEX_TVSHOW = 2;
+ const PLEX_SEASON = 3;
+ const PLEX_EPISODE = 4;
+ const PLEX_MOVIE = 1;
const PLEX_PLAYLIST = 15;
/**
@@ -300,7 +299,7 @@ class Plex_XML_Data
public static function getKeyFromFullUri($uri)
{
- $key = '';
+ $key = '';
$puri = parse_url($uri);
if ($puri['scheme'] == 'library') {
// We ignore library uuid (= $puri['host'])
@@ -371,7 +370,7 @@ class Plex_XML_Data
$xml->addAttribute('friendlyName', self::getServerName());
$xml->addAttribute('machineIdentifier', self::getMachineIdentifier());
- $myplex_username = self::getMyPlexUsername();
+ $myplex_username = self::getMyPlexUsername();
$myplex_authtoken = self::getMyPlexAuthToken();
$myplex_published = self::getMyPlexPublished();
if ($myplex_username) {
@@ -477,7 +476,7 @@ class Plex_XML_Data
$dir->addAttribute('machineIdentifier', self::getMachineIdentifier());
$dir->addAttribute('serverName', self::getServerName());
$dir->addAttribute('path', self::getSectionUri($id));
- $ip = self::getServerAddress();
+ $ip = self::getServerAddress();
$port = self::getServerPort();
$dir->addAttribute('host', $ip);
$dir->addAttribute('local', ($ip == "127.0.0.1") ? '1' : '0');
@@ -749,7 +748,7 @@ class Plex_XML_Data
self::addCatalogIdentity($xml, $catalog);
self::setSectionXContent($xml, $catalog, 'album');
- $data = array();
+ $data = array();
$data['album'] = $albums;
self::_setCustomView($xml, $data);
}
@@ -815,7 +814,7 @@ class Plex_XML_Data
public static function addArtist(SimpleXMLElement $xml, Artist $artist)
{
$xdir = $xml->addChild('Directory');
- $id = self::getArtistId($artist->id);
+ $id = self::getArtistId($artist->id);
$xdir->addAttribute('ratingKey', $id);
$xdir->addAttribute('type', 'artist');
$xdir->addAttribute('title', $artist->name);
@@ -823,7 +822,7 @@ class Plex_XML_Data
$xdir->addAttribute('addedAt', '');
$xdir->addAttribute('updatedAt', '');
- $rating = new Rating($artist->id, "artist");
+ $rating = new Rating($artist->id, "artist");
$rating_value = $rating->get_average_rating();
if ($rating_value > 0) {
$xdir->addAttribute('rating', intval($rating_value * 2));
@@ -845,8 +844,8 @@ class Plex_XML_Data
protected static function addArtistThumb(SimpleXMLElement $xml, $artist_id, $attrthumb = 'thumb')
{
- $id = self::getArtistId($artist_id);
- $art = new Art($artist_id, 'artist');
+ $id = self::getArtistId($artist_id);
+ $art = new Art($artist_id, 'artist');
$thumb = '';
if ($art->get_db()) {
$thumb = self::getMetadataUri($id) . '/thumb/' . $id;
@@ -856,7 +855,7 @@ class Plex_XML_Data
public static function addAlbum(SimpleXMLElement $xml, Album $album)
{
- $id = self::getAlbumId($album->id);
+ $id = self::getAlbumId($album->id);
$xdir = $xml->addChild('Directory');
self::addAlbumMeta($xdir, $album);
$xdir->addAttribute('ratingKey', $id);
@@ -871,7 +870,7 @@ class Plex_XML_Data
$xdir->addAttribute('year', $album->year);
}
- $rating = new Rating($album->id, "album");
+ $rating = new Rating($album->id, "album");
$rating_value = $rating->get_average_rating();
if ($rating_value > 0) {
$xdir->addAttribute('rating', intval($rating_value * 2));
@@ -907,7 +906,7 @@ class Plex_XML_Data
public static function addTVShow(SimpleXMLElement $xml, TVShow $tvshow)
{
- $id = self::getTVShowId($tvshow->id);
+ $id = self::getTVShowId($tvshow->id);
$xdir = $xml->addChild('Directory');
$xdir->addAttribute('ratingKey', $id);
$xdir->addAttribute('key', self::getMetadataUri($id) . '/children');
@@ -917,7 +916,7 @@ class Plex_XML_Data
$xdir->addAttribute('title', $tvshow->f_name);
$xdir->addAttribute('titleSort', $tvshow->name);
$xdir->addAttribute('index', '1');
- $rating = new Rating($tvshow->id, "tvshow");
+ $rating = new Rating($tvshow->id, "tvshow");
$rating_value = $rating->get_average_rating();
if ($rating_value > 0) {
$xdir->addAttribute('rating', intval($rating_value * 2));
@@ -1050,7 +1049,7 @@ class Plex_XML_Data
public static function addTVShowSeason(SimpleXMLElement $xml, TVShow_Season $season)
{
- $id = self::getTVShowSeasonId($season->id);
+ $id = self::getTVShowSeasonId($season->id);
$xdir = $xml->addChild('Directory');
$xdir->addAttribute('ratingKey', $id);
$xdir->addAttribute('key', self::getMetadataUri($id) . '/children');
@@ -1099,57 +1098,57 @@ class Plex_XML_Data
public static function addSong(SimpleXMLElement $xml, Song $song)
{
- $xdir = $xml->addChild('Track');
- self::addSongMeta($xdir, $song);
- $time = $song->time * 1000;
- $xdir->addAttribute('title', $song->title);
- $id = self::getAlbumId($song->id);
- $albumid = self::getAlbumId($song->album);
- $artistid = self::getAlbumId($song->artist);
- $xdir->addAttribute('grandparentRatingKey', $artistid);
- $xdir->addAttribute('parentRatingKey', $albumid);
- $xdir->addAttribute('grandparentKey', self::getMetadataUri($albumid));
- $xdir->addAttribute('parentKey', self::getMetadataUri($albumid));
- $xdir->addAttribute('grandparentTitle', $song->f_artist);
- $xdir->addAttribute('parentTitle', $song->f_album);
- $xdir->addAttribute('originalTitle', $song->f_artist);
- $xdir->addAttribute('summary', '');
- $xdir->addAttribute('art', self::getMetadataUri($id) . '/art/' . $id);
- $xdir->addAttribute('grandparentThumb', self::getMetadataUri($artistid) . '/thumb/' . $artistid);
- $xdir->addAttribute('parentThumb', self::getMetadataUri($albumid) . '/thumb/' . $albumid);
- $xdir->addAttribute('thumb', self::getMetadataUri($albumid) . '/thumb/' . $albumid); // No song art, set album art
+ $xdir = $xml->addChild('Track');
+ self::addSongMeta($xdir, $song);
+ $time = $song->time * 1000;
+ $xdir->addAttribute('title', $song->title);
+ $id = self::getAlbumId($song->id);
+ $albumid = self::getAlbumId($song->album);
+ $artistid = self::getAlbumId($song->artist);
+ $xdir->addAttribute('grandparentRatingKey', $artistid);
+ $xdir->addAttribute('parentRatingKey', $albumid);
+ $xdir->addAttribute('grandparentKey', self::getMetadataUri($albumid));
+ $xdir->addAttribute('parentKey', self::getMetadataUri($albumid));
+ $xdir->addAttribute('grandparentTitle', $song->f_artist);
+ $xdir->addAttribute('parentTitle', $song->f_album);
+ $xdir->addAttribute('originalTitle', $song->f_artist);
+ $xdir->addAttribute('summary', '');
+ $xdir->addAttribute('art', self::getMetadataUri($id) . '/art/' . $id);
+ $xdir->addAttribute('grandparentThumb', self::getMetadataUri($artistid) . '/thumb/' . $artistid);
+ $xdir->addAttribute('parentThumb', self::getMetadataUri($albumid) . '/thumb/' . $albumid);
+ $xdir->addAttribute('thumb', self::getMetadataUri($albumid) . '/thumb/' . $albumid); // No song art, set album art
$xdir->addAttribute('index', $song->track);
- $xdir->addAttribute('duration', $time);
- $xdir->addAttribute('type', 'track');
- $xdir->addAttribute('addedAt', '');
- $xdir->addAttribute('updatedAt', '');
+ $xdir->addAttribute('duration', $time);
+ $xdir->addAttribute('type', 'track');
+ $xdir->addAttribute('addedAt', '');
+ $xdir->addAttribute('updatedAt', '');
- $rating = new Rating($song->id, "song");
- $rating_value = $rating->get_average_rating();
- if ($rating_value > 0) {
- $xdir->addAttribute('rating', intval($rating_value * 2));
- }
+ $rating = new Rating($song->id, "song");
+ $rating_value = $rating->get_average_rating();
+ if ($rating_value > 0) {
+ $xdir->addAttribute('rating', intval($rating_value * 2));
+ }
- $xmedia = $xdir->addChild('Media');
- $mediaid = self::getSongId($song->id);
- $xmedia->addAttribute('id', $mediaid);
- $xmedia->addAttribute('duration', $time);
- $xmedia->addAttribute('bitrate', intval($song->bitrate / 1000));
- $xmedia->addAttribute('audioChannels', $song->channels);
+ $xmedia = $xdir->addChild('Media');
+ $mediaid = self::getSongId($song->id);
+ $xmedia->addAttribute('id', $mediaid);
+ $xmedia->addAttribute('duration', $time);
+ $xmedia->addAttribute('bitrate', intval($song->bitrate / 1000));
+ $xmedia->addAttribute('audioChannels', $song->channels);
// Type != Codec != Container, but that's how Ampache works today...
$xmedia->addAttribute('audioCodec', $song->type);
- $xmedia->addAttribute('container', $song->type);
+ $xmedia->addAttribute('container', $song->type);
- $xpart = $xmedia->addChild('Part');
- $partid = self::getPartId($mediaid);
- $xpart->addAttribute('id', $partid);
- $xpart->addAttribute('key', self::getPartUri($partid, $song->type));
- $xpart->addAttribute('duration', $time);
- $xpart->addAttribute('file', $song->file);
- $xpart->addAttribute('size', $song->size);
- $xpart->addAttribute('container', $song->type);
+ $xpart = $xmedia->addChild('Part');
+ $partid = self::getPartId($mediaid);
+ $xpart->addAttribute('id', $partid);
+ $xpart->addAttribute('key', self::getPartUri($partid, $song->type));
+ $xpart->addAttribute('duration', $time);
+ $xpart->addAttribute('file', $song->file);
+ $xpart->addAttribute('size', $song->size);
+ $xpart->addAttribute('container', $song->type);
- return $xdir;
+ return $xdir;
}
public static function addSongMeta(SimpleXMLElement $xml, Song $song)
@@ -1179,7 +1178,7 @@ class Plex_XML_Data
public static function addEpisode(SimpleXMLElement $xml, TVShow_Episode $episode, $details = false)
{
- $xvid = self::addVideo($xml, $episode, $details);
+ $xvid = self::addVideo($xml, $episode, $details);
$seasonid = self::getTVShowSeasonId($episode->season);
$xvid->addAttribute('parentRatingKey', $seasonid);
$xvid->addAttribute('parentKey', self::getMetadataUri($seasonid));
@@ -1204,7 +1203,7 @@ class Plex_XML_Data
private static function addVideo(SimpleXMLElement $xml, Video $video, $details = false)
{
- $id = self::getVideoId($video->id);
+ $id = self::getVideoId($video->id);
$xvid = $xml->addChild('Video');
$xvid->addAttribute('ratingKey', $id);
$xvid->addAttribute('key', self::getMetadataUri($id));
@@ -1216,7 +1215,7 @@ class Plex_XML_Data
}
$xvid->addAttribute('originallyAvailableAt', $video->f_release_date);
}
- $rating = new Rating($video->id, "video");
+ $rating = new Rating($video->id, "video");
$rating_value = $rating->get_average_rating();
if ($rating_value > 0) {
$xvid->addAttribute('rating', intval($rating_value * 2));
@@ -1227,29 +1226,29 @@ class Plex_XML_Data
$xvid->addAttribute('updatedAt', '');
$xvid->addAttribute('thumb', self::getMetadataUri($id) . '/thumb/' . $id);
- $xmedia = $xvid->addChild('Media');
- $xmedia->addAttribute('id', $id); // Same ID that video => OK?
+ $xmedia = $xvid->addChild('Media');
+ $xmedia->addAttribute('id', $id); // Same ID that video => OK?
$xmedia->addAttribute('duration', $time);
- $xmedia->addAttribute('bitrate', intval($video->bitrate / 1000));
- $xmedia->addAttribute('audioChannels', $video->channels);
+ $xmedia->addAttribute('bitrate', intval($video->bitrate / 1000));
+ $xmedia->addAttribute('audioChannels', $video->channels);
// Type != Codec != Container, but that's how Ampache works today...
$xmedia->addAttribute('audioCodec', $video->audio_codec);
- $xmedia->addAttribute('videoCodec', $video->video_codec);
- $xmedia->addAttribute('container', $video->type);
- $xmedia->addAttribute('width', $video->resolution_x);
- $xmedia->addAttribute('height', $video->resolution_y);
+ $xmedia->addAttribute('videoCodec', $video->video_codec);
+ $xmedia->addAttribute('container', $video->type);
+ $xmedia->addAttribute('width', $video->resolution_x);
+ $xmedia->addAttribute('height', $video->resolution_y);
//$xmedia->addAttribute('videoResolution', 'sd'); // TODO
//$xmedia->addAttribute('aspectRatio', '1.78'); // TODO
$xmedia->addAttribute('videoFrameRate', intval(ceil($video->frame_rate)) . 'p');
- $xpart = $xmedia->addChild('Part');
- $partid = self::getPartId($id);
- $xpart->addAttribute('id', $partid);
- $xpart->addAttribute('key', self::getPartUri($partid, $video->type));
- $xpart->addAttribute('duration', $time);
- $xpart->addAttribute('file', $video->file);
- $xpart->addAttribute('size', $video->size);
- $xpart->addAttribute('container', $video->type);
+ $xpart = $xmedia->addChild('Part');
+ $partid = self::getPartId($id);
+ $xpart->addAttribute('id', $partid);
+ $xpart->addAttribute('key', self::getPartUri($partid, $video->type));
+ $xpart->addAttribute('duration', $time);
+ $xpart->addAttribute('file', $video->file);
+ $xpart->addAttribute('size', $video->size);
+ $xpart->addAttribute('container', $video->type);
// TODO: support Writer/Director tags here as part of Video/
/*
@@ -1267,29 +1266,29 @@ class Plex_XML_Data
}
}
- if ($details) {
- // Subtitles
+ if ($details) {
+ // Subtitles
$subtitles = $video->get_subtitles();
- foreach ($subtitles as $subtitle) {
- $streamid = hexdec(bin2hex($subtitle['lang_code'])) . $partid;
- $xstream = $xpart->addChild('Stream');
- $xstream->addAttribute('id', $streamid);
- $xstream->addAttribute('key', '/library/streams/' . $streamid);
- $xstream->addAttribute('streamType', '3');
- $xstream->addAttribute('codec', 'srt');
- $xstream->addAttribute('language', $subtitle['lang_name']);
- $xstream->addAttribute('languageCode', $subtitle['lang_code']);
- $xstream->addAttribute('format', 'srt');
- }
+ foreach ($subtitles as $subtitle) {
+ $streamid = hexdec(bin2hex($subtitle['lang_code'])) . $partid;
+ $xstream = $xpart->addChild('Stream');
+ $xstream->addAttribute('id', $streamid);
+ $xstream->addAttribute('key', '/library/streams/' . $streamid);
+ $xstream->addAttribute('streamType', '3');
+ $xstream->addAttribute('codec', 'srt');
+ $xstream->addAttribute('language', $subtitle['lang_name']);
+ $xstream->addAttribute('languageCode', $subtitle['lang_code']);
+ $xstream->addAttribute('format', 'srt');
+ }
// TODO: support real audio/video streams!
/*
*/
- }
+ }
- return $xvid;
+ return $xvid;
}
public static function setPlaylists(SimpleXMLElement $xml)
@@ -1304,7 +1303,7 @@ class Plex_XML_Data
public static function addPlaylist(SimpleXMLElement $xml, $playlist)
{
- $id = self::getPlaylistId($playlist->id);
+ $id = self::getPlaylistId($playlist->id);
$xpl = $xml->addChild('Playlist');
$xpl->addAttribute('ratingKey', $id);
$xpl->addAttribute('key', '/playlists/' . $id . '/items');
@@ -1315,7 +1314,7 @@ class Plex_XML_Data
//$xpl->addAttribute('composite', '');
$xpl->addAttribute('playlistType', 'audio');
$xpl->addAttribute('duration', $playlist->get_total_duration() * 1000);
- $xpl->addAttribute('leafCount', $playlist->get_song_count());
+ $xpl->addAttribute('leafCount', $playlist->get_media_count('song'));
$xpl->addAttribute('addedAt', '');
$xpl->addAttribute('updatedAt', '');
}
@@ -1323,7 +1322,7 @@ class Plex_XML_Data
public static function setPlaylistItems(SimpleXMLElement $xml, $playlist)
{
$xml->addAttribute('duration', $playlist->get_total_duration() * 1000);
- $xml->addAttribute('leafCount', $playlist->get_song_count());
+ $xml->addAttribute('leafCount', $playlist->get_media_count('song'));
$items = $playlist->get_items();
self::addPlaylistsItems($xml, $items);
}
@@ -1359,7 +1358,7 @@ class Plex_XML_Data
$id = self::getKeyFromMetadataUri($key);
} elseif (!empty($uri)) {
$key = self::getKeyFromFullUri($uri);
- $id = self::getKeyFromMetadataUri($key);
+ $id = self::getKeyFromMetadataUri($key);
}
$plmedias = array();
@@ -1397,14 +1396,14 @@ class Plex_XML_Data
$xml->addAttribute('playQueueVersion', '1');
$items = $GLOBALS['user']->playlist->get_items();
- $c = count($items);
+ $c = count($items);
if ($c > 0) {
self::addPlaylistsItems($xml, $items, 'playQueueItemID');
// TODO: This should be the real selected item.
// But we're missing this information in Ampache playlist
$currentIndex = 0;
- $currentItem = $items[$currentIndex];
+ $currentItem = $items[$currentIndex];
if (isset($currentItem['track_id'])) {
$xml->addAttribute('playQueueSelectedItemID', $currentItem['track_id']);
}
@@ -1417,8 +1416,8 @@ class Plex_XML_Data
public static function createMyPlexAccount()
{
- $xml = new SimpleXMLElement('');
- $myplex_username = self::getMyPlexUsername();
+ $xml = new SimpleXMLElement('');
+ $myplex_username = self::getMyPlexUsername();
$myplex_authtoken = self::getMyPlexAuthToken();
$myplex_published = self::getMyPlexPublished();
if ($myplex_username) {
@@ -1575,7 +1574,7 @@ class Plex_XML_Data
public static function createLibraryItem($id)
{
$item = null;
- $oid = self::getAmpacheId($id);
+ $oid = self::getAmpacheId($id);
$type = self::getLibraryItemType($id);
if ($type) {
@@ -1738,10 +1737,11 @@ class Plex_XML_Data
protected static function getPathDelimiter()
{
- if (strpos(PHP_OS, 'WIN') === 0)
+ if (strpos(PHP_OS, 'WIN') === 0) {
return '\\';
- else
+ } else {
return '/';
+ }
}
public static function setBrowseService(SimpleXMLElement $xml, $path)
@@ -1781,12 +1781,12 @@ class Plex_XML_Data
public static function addDirPath(SimpleXMLElement $xml, $path, $title='', $isHome=false)
{
$delim = self::getPathDelimiter();
- $dir = $xml->addChild('Path');
+ $dir = $xml->addChild('Path');
if ($isHome) {
$dir->addAttribute('isHome', '1');
}
if (empty($title)) {
- $pp = explode($delim, $path);
+ $pp = explode($delim, $path);
$title = $pp[count($pp)-1];
if (empty($title)) {
$title = $path;
@@ -1846,7 +1846,7 @@ class Plex_XML_Data
public static function addPhoto(SimpleXMLElement $xml, $id, $kind = 'default')
{
$xart = $xml->addChild('Photo');
- $uri = self::getMetadataUri($id) . '/' . self::getPhotoPlexKind($kind) . '/' . $id;
+ $uri = self::getMetadataUri($id) . '/' . self::getPhotoPlexKind($kind) . '/' . $id;
$xart->addAttribute('key', $uri);
$xart->addAttribute('ratingKey', $uri);
$xart->addAttribute('thumb', $uri);
diff --git a/sources/lib/class/plugin.class.php b/sources/lib/class/plugin.class.php
index 767c646..882c67d 100644
--- a/sources/lib/class/plugin.class.php
+++ b/sources/lib/class/plugin.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -41,7 +41,6 @@ class Plugin
}
return true;
-
} // Constructor
@@ -50,21 +49,34 @@ class Plugin
* 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]
*/
- public function _get_info($name)
+ public function _get_info($cname)
{
- /* Require the file we want */
- require_once AmpConfig::get('prefix') . '/modules/plugins/' . $name . '.plugin.php';
+ try {
+ $basedir = AmpConfig::get('prefix') . '/modules/plugins';
+ if (is_dir($basedir . '/' . $cname)) {
+ $name = $cname;
+ } else {
+ $name = 'ampache-' . strtolower($cname);
+ }
+
+ /* Require the file we want */
+ if (!@include_once($basedir . '/' . $name . '/' . $cname . '.plugin.php')) {
+ debug_event('plugin', 'Cannot include plugin `' . $cname . '`.', 1);
+ return false;
+ }
- $plugin_name = "Ampache$name";
+ $plugin_name = "Ampache$cname";
+ $this->_plugin = new $plugin_name();
- $this->_plugin = new $plugin_name();
-
- if (!$this->is_valid()) {
+ if (!$this->is_valid()) {
+ return false;
+ }
+ } catch (Exception $ex) {
+ debug_event('plugin', 'Error when initializing plugin `' . $cname . '`: ' . $ex->getMessage(), 1);
return false;
}
return true;
-
} // _get_info
/**
@@ -75,13 +87,15 @@ class Plugin
{
// make static cache for optimization when multiple call
static $plugins_list = array();
- if (isset($plugins_list[$type]))
+ if (isset($plugins_list[$type])) {
return $plugins_list[$type];
+ }
$plugins_list[$type] = array();
// Open up the plugin dir
- $handle = opendir(AmpConfig::get('prefix') . '/modules/plugins');
+ $basedir = AmpConfig::get('prefix') . '/modules/plugins';
+ $handle = opendir($basedir);
if (!is_resource($handle)) {
debug_event('Plugins','Unable to read plugins directory','1');
@@ -89,34 +103,51 @@ class Plugin
// Recurse the directory
while (false !== ($file = readdir($handle))) {
- // Ignore non-plugin files
- if (substr($file,-10,10) != 'plugin.php') { continue; }
- if (is_dir($file)) { continue; }
- $plugin_name = basename($file,'.plugin.php');
+ if ($file === '.' || $file === '..') {
+ continue;
+ }
+ // Take care of directories only
+ if (!is_dir($basedir . '/' . $file)) {
+ debug_event('Plugins', $file . ' is not a directory.', 3);
+ continue;
+ }
+
+ // If directory name start with ampache-, this is an external plugin and some parsing is required
+ if (strpos($file, "ampache-") === 0) {
+ $cfile = ucfirst(substr($file, 8));
+ } else {
+ $cfile = $file;
+ }
+
+ // Make sure the plugin base file exists inside the plugin directory
+ if (! file_exists($basedir . '/' . $file . '/' . $cfile . '.plugin.php')) {
+ debug_event('Plugins', 'Missing class for ' . $cfile, 3);
+ continue;
+ }
+
if ($type != '') {
- $plugin = new Plugin($plugin_name);
+ $plugin = new Plugin($cfile);
if (! Plugin::is_installed($plugin->_plugin->name)) {
debug_event('Plugins', 'Plugin ' . $plugin->_plugin->name . ' is not installed, skipping', 6);
continue;
}
if (! $plugin->is_valid()) {
- debug_event('Plugins', 'Plugin ' . $plugin_name . ' is not valid, skipping', 6);
+ debug_event('Plugins', 'Plugin ' . $cfile . ' is not valid, skipping', 6);
continue;
}
if (! method_exists($plugin->_plugin, $type)) {
- debug_event('Plugins', 'Plugin ' . $plugin_name . ' does not support ' . $type . ', skipping', 6);
+ debug_event('Plugins', 'Plugin ' . $cfile . ' does not support ' . $type . ', skipping', 6);
continue;
}
}
// It's a plugin record it
- $plugins_list[$type][$plugin_name] = $plugin_name;
+ $plugins_list[$type][$cfile] = $cfile;
} // end while
// Little stupid but hey
ksort($plugins_list[$type]);
return $plugins_list[$type];
-
} // get_plugins
/**
@@ -166,7 +197,6 @@ class Plugin
// We've passed all of the tests
return true;
-
} // is_valid
/**
@@ -178,7 +208,6 @@ class Plugin
{
/* All we do is check the version */
return self::get_plugin_version($plugin_name);
-
} // is_installed
/**
@@ -206,7 +235,6 @@ class Plugin
$this->_plugin->uninstall();
$this->remove_plugin_version();
-
} // uninstall
/**
@@ -241,15 +269,14 @@ class Plugin
{
$name = Dba::escape('Plugin_' . $plugin_name);
- $sql = "SELECT * FROM `update_info` WHERE `key`='$name'";
- $db_results = Dba::read($sql);
+ $sql = "SELECT * FROM `update_info` WHERE `key` = ?";
+ $db_results = Dba::read($sql, array($name));
if ($results = Dba::fetch_assoc($db_results)) {
return $results['value'];
}
return false;
-
} // get_plugin_version
/**
@@ -258,13 +285,12 @@ class Plugin
*/
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);
$results = Dba::fetch_assoc($db_results);
return $results['value'];
-
} // get_ampache_db_version
/**
@@ -274,13 +300,12 @@ class Plugin
public function set_plugin_version($version)
{
$name = Dba::escape('Plugin_' . $this->_plugin->name);
- $version = Dba::escape($version);
+ $version = Dba::escape($version);
$sql = "REPLACE INTO `update_info` SET `key`='$name', `value`='$version'";
Dba::write($sql);
return true;
-
} // set_plugin_version
/**
@@ -295,7 +320,6 @@ class Plugin
Dba::write($sql);
return true;
-
} // remove_plugin_version
-
} //end plugin class
+
diff --git a/sources/lib/class/podcast.class.php b/sources/lib/class/podcast.class.php
new file mode 100644
index 0000000..1a503a3
--- /dev/null
+++ b/sources/lib/class/podcast.class.php
@@ -0,0 +1,481 @@
+.
+ *
+ */
+
+class Podcast extends database_object implements library_item
+{
+ /* Variables from DB */
+ public $id;
+ public $catalog;
+ public $feed;
+ public $title;
+ public $website;
+ public $description;
+ public $language;
+ public $copyright;
+ public $generator;
+ public $lastbuilddate;
+ public $lastsync;
+
+ public $episodes;
+ public $f_title;
+ public $f_description;
+ public $f_language;
+ public $f_copyright;
+ public $f_generator;
+ public $f_lastbuilddate;
+ public $f_lastsync;
+ public $link;
+ public $f_link;
+
+ /**
+ * Podcast
+ * Takes the ID of the podcast and pulls the info from the db
+ */
+ public function __construct($id='')
+ {
+ /* If they failed to pass in an id, just run for it */
+ if (!$id) {
+ return false;
+ }
+
+ /* Get the information from the db */
+ $info = $this->get_info($id);
+
+ foreach ($info as $key=>$value) {
+ $this->$key = $value;
+ } // foreach info
+
+ return true;
+ } //constructor
+
+ /**
+ * gc
+ *
+ * This cleans out unused podcasts
+ */
+ public static function gc()
+ {
+ }
+
+ /**
+ * get_catalogs
+ *
+ * Get all catalog ids related to this item.
+ * @return int[]
+ */
+ public function get_catalogs()
+ {
+ return array($this->catalog);
+ }
+
+ /**
+ * get_episodes
+ * gets all episodes for this tv show
+ */
+ public function get_episodes($state_filter = '')
+ {
+ $params = array();
+ $sql = "SELECT `podcast_episode`.`id` FROM `podcast_episode` ";
+ if (AmpConfig::get('catalog_disable')) {
+ $sql .= "LEFT JOIN `podcast` ON `podcast`.`id` = `podcast_episode`.`podcast` ";
+ $sql .= "LEFT JOIN `catalog` ON `catalog`.`id` = `podcast`.`catalog` ";
+ }
+ $sql .= "WHERE `podcast_episode`.`podcast`='" . Dba::escape($this->id) . "' ";
+ if (!empty($state_filter)) {
+ $sql .= "AND `podcast_episode`.`state` = ? ";
+ $params[] = $state_filter;
+ }
+ if (AmpConfig::get('catalog_disable')) {
+ $sql .= "AND `catalog`.`enabled` = '1' ";
+ }
+ $sql .= "ORDER BY `podcast_episode`.`pubdate` DESC";
+ $db_results = Dba::read($sql, $params);
+
+ $results = array();
+ while ($r = Dba::fetch_assoc($db_results)) {
+ $results[] = $r['id'];
+ }
+
+ return $results;
+ } // get_episodes
+
+ /**
+ * _get_extra info
+ * This returns the extra information for the podcast, this means totals etc
+ */
+ private function _get_extra_info()
+ {
+ // Try to find it in the cache and save ourselves the trouble
+ if (parent::is_cached('podcast_extra', $this->id) ) {
+ $row = parent::get_from_cache('podcast_extra', $this->id);
+ } else {
+ $sql = "SELECT COUNT(`podcast_episode`.`id`) AS `episode_count` FROM `podcast_episode` " .
+ "WHERE `podcast_episode`.`podcast` = ?";
+ $db_results = Dba::read($sql, array($this->id));
+ $row = Dba::fetch_assoc($db_results);
+
+ parent::add_to_cache('podcast_extra',$this->id,$row);
+ }
+
+ /* Set Object Vars */
+ $this->episodes = $row['episode_count'];
+
+ return $row;
+ } // _get_extra_info
+
+ /**
+ * format
+ * this function takes the object and reformats some values
+ */
+ public function format($details = true)
+ {
+ $this->f_title = scrub_out($this->title);
+ $this->f_description = scrub_out($this->description);
+ $this->f_language = scrub_out($this->language);
+ $this->f_copyright = scrub_out($this->copyright);
+ $this->f_generator = scrub_out($this->generator);
+ $this->f_website = scrub_out($this->website);
+ $this->f_lastbuilddate = date("m\/d\/Y - H:i", $this->lastbuilddate);
+ $this->f_lastsync = date("m\/d\/Y - H:i", $this->lastsync);
+ $this->link = AmpConfig::get('web_path') . '/podcast.php?action=show&podcast=' . $this->id;
+ $this->f_link = '' . $this->f_title . '';
+
+ if ($details) {
+ $this->_get_extra_info();
+ }
+
+ return true;
+ }
+
+ public function get_keywords()
+ {
+ $keywords = array();
+ $keywords['podcast'] = array('important' => true,
+ 'label' => T_('Podcast'),
+ 'value' => $this->f_title);
+
+ return $keywords;
+ }
+
+ public function get_fullname()
+ {
+ return $this->f_title;
+ }
+
+ public function get_parent()
+ {
+ return null;
+ }
+
+ public function get_childrens()
+ {
+ return array('podcast_episode' => $this->get_episodes());
+ }
+
+ public function search_childrens($name)
+ {
+ return array();
+ }
+
+ public function get_medias($filter_type = null)
+ {
+ $medias = array();
+ if (!$filter_type || $filter_type == 'podcast_episode') {
+ $episodes = $this->get_episodes('completed');
+ foreach ($episodes as $episode_id) {
+ $medias[] = array(
+ 'object_type' => 'podcast_episode',
+ 'object_id' => $episode_id
+ );
+ }
+ }
+ return $medias;
+ }
+
+ public function get_user_owner()
+ {
+ return null;
+ }
+
+ public function get_default_art_kind()
+ {
+ return 'default';
+ }
+
+ public function get_description()
+ {
+ return $this->f_description;
+ }
+
+ public function display_art($thumb = 2)
+ {
+ if (Art::has_db($this->id, 'podcast')) {
+ Art::display('podcast', $this->id, $this->get_fullname(), $thumb, $this->link);
+ }
+ }
+
+ /**
+ * update
+ * This takes a key'd array of data and updates the current podcast
+ */
+ public function update(array $data)
+ {
+ $feed = isset($data['feed']) ? $data['feed'] : $this->feed;
+ $title = isset($data['title']) ? scrub_in($data['title']) : $this->title;
+ $website = isset($data['website']) ? scrub_in($data['website']) : $this->website;
+ $description = isset($data['description']) ? scrub_in($data['description']) : $this->description;
+ $generator = isset($data['generator']) ? scrub_in($data['generator']) : $this->generator;
+ $copyright = isset($data['copyright']) ? scrub_in($data['copyright']) : $this->copyright;
+
+ if (strpos($feed, "http://") !== 0 && strpos($feed, "https://") !== 0) {
+ debug_event('podcast', 'Podcast update canceled, bad feed url.', 1);
+ return $this->id;
+ }
+
+ $sql = 'UPDATE `podcast` SET `feed` = ?, `title` = ?, `website` = ?, `description` = ?, `generator` = ?, `copyright` = ? WHERE `id` = ?';
+ Dba::write($sql, array($feed, $title, $website, $description, $generator, $copyright, $this->id));
+
+ $this->feed = $feed;
+ $this->title = $title;
+ $this->website = $website;
+ $this->description = $description;
+ $this->generator = $generator;
+ $this->copyright = $copyright;
+
+ return $this->id;
+ }
+
+ public static function create(array $data)
+ {
+ $feed = $data['feed'];
+ // Feed must be http/https
+ if (strpos($feed, "http://") !== 0 && strpos($feed, "https://") !== 0) {
+ AmpError::add('feed', T_('Wrong feed url'));
+ }
+
+ $catalog_id = intval($data['catalog']);
+ if ($catalog_id <= 0) {
+ AmpError::add('catalog', T_('Target catalog required'));
+ } else {
+ $catalog = Catalog::create_from_id($catalog_id);
+ if ($catalog->gather_types !== "podcast") {
+ AmpError::add('catalog', T_('Wrong target catalog type'));
+ }
+ }
+
+ if (AmpError::occurred()) {
+ return false;
+ }
+
+ $title = T_('Unknown');
+ $website = null;
+ $description = null;
+ $language = null;
+ $copyright = null;
+ $generator = null;
+ $lastbuilddate = 0;
+ $episodes = array();
+ $arturl = '';
+
+ $xmlstr = file_get_contents($feed);
+ if ($xmlstr === false) {
+ AmpError::add('feed', T_('Cannot access the feed.'));
+ } else {
+ $xml = simplexml_load_string($xmlstr);
+ if ($xml === false) {
+ AmpError::add('feed', T_('Cannot read the feed.'));
+ } else {
+ $title = html_entity_decode($xml->channel->title);
+ $website = $xml->channel->link;
+ $description = html_entity_decode($xml->channel->description);
+ $language = $xml->channel->language;
+ $copyright = html_entity_decode($xml->channel->copyright);
+ $generator = html_entity_decode($xml->channel->generator);
+ $lastbuilddatestr = $xml->channel->lastBuildDate;
+ if ($lastbuilddatestr) {
+ $lastbuilddate = strtotime($lastbuilddatestr);
+ }
+
+ if ($xml->channel->image) {
+ $arturl = $xml->channel->image->url;
+ }
+
+ $episodes = $xml->channel->item;
+ }
+ }
+
+ if (AmpError::occurred()) {
+ return false;
+ }
+
+ $sql = "INSERT INTO `podcast` (`feed`, `catalog`, `title`, `website`, `description`, `language`, `copyright`, `generator`, `lastbuilddate`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
+ $db_results = Dba::write($sql, array($feed, $catalog_id, $title, $website, $description, $language, $copyright, $generator, $lastbuilddate));
+ if ($db_results) {
+ $id = Dba::insert_id();
+ $podcast = new Podcast($id);
+ $dirpath = $podcast->get_root_path();
+ if (!is_dir($dirpath)) {
+ if (mkdir($dirpath) === false) {
+ debug_event('podcast', 'Cannot create directory ' . $dirpath, 1);
+ }
+ }
+ if (!empty($arturl)) {
+ $art = new Art($id, 'podcast');
+ $art->insert_url($arturl);
+ }
+ if (count($episodes) > 0) {
+ $podcast->add_episodes($episodes);
+ }
+ }
+
+ return $db_results;
+ }
+
+ public function add_episodes($episodes, $afterdate=0, $gather=false)
+ {
+ foreach ($episodes as $episode) {
+ $this->add_episode($episode, $afterdate);
+ }
+
+ // Select episodes to download
+ $dlnb = AmpConfig::get('podcast_new_download');
+ if ($dlnb != 0) {
+ $sql = "SELECT `podcast_episode`.`id` FROM `podcast_episode` INNER JOIN `podcast` ON `podcast`.`id` = `podcast_episode`.`podcast` " .
+ "WHERE `podcast`.`id` = ? AND `podcast_episode`.`addition_time` > `podcast`.`lastsync` " .
+ "ORDER BY `podcast_episode`.`pubdate` DESC";
+ if ($dlnb != -1) {
+ $sql .= " LIMIT " . $dlnb;
+ }
+ $db_results = Dba::read($sql, array($this->id));
+ while ($row = Dba::fetch_row($db_results)) {
+ $episode = new Podcast_Episode($row[0]);
+ $episode->change_state('pending');
+ if ($gather) {
+ $episode->gather();
+ }
+ }
+ }
+ // Remove items outside limit
+ $keepnb = AmpConfig::get('podcast_keep');
+ if ($keepnb > 0) {
+ $sql = "SELECT `podcast_episode`.`id` FROM `podcast_episode` WHERE `podcast_episode`.`podcast` = ? " .
+ "ORDER BY `podcast_episode`.`pubdate` DESC LIMIT " . $keepnb . ",18446744073709551615";
+ $db_results = Dba::read($sql, array($this->id));
+ while ($row = Dba::fetch_row($db_results)) {
+ $episode = new Podcast_Episode($row[0]);
+ $episode->remove();
+ }
+ }
+ $this->update_lastsync(time());
+ }
+
+ private function add_episode(SimpleXMLElement $episode, $afterdate=0)
+ {
+ debug_event('podcast', 'Adding new episode to podcast ' . $this->id . '...', 5);
+
+ $title = html_entity_decode($episode->title);
+ $website = $episode->link;
+ $guid = $episode->guid;
+ $description = html_entity_decode($episode->description);
+ $author = html_entity_decode($episode->author);
+ $category = html_entity_decode($episode->category);
+ $source = null;
+ $time = 0;
+ if ($episode->enclosure) {
+ $source = $episode->enclosure['url'];
+ }
+ $itunes = $episode->children('itunes', true);
+ if ($itunes) {
+ $ptime = date_parse($itunes->duration);
+ $time = $ptime['hour'] * 3600 + $ptime['minute'] * 60 + $ptime['second'];
+ }
+ $pubdate = 0;
+ $pubdatestr = $episode->pubDate;
+ if ($pubdatestr) {
+ $pubdate = strtotime($pubdatestr);
+ }
+
+ if ($pubdate <= 0) {
+ debug_log('podcast', 'Invalid episode publication date, skipped', 3);
+ return false;
+ }
+
+ if ($pubdate > $afterdate) {
+ $sql = "INSERT INTO `podcast_episode` (`title`, `guid`, `podcast`, `state`, `source`, `website`, `description`, `author`, `category`, `time`, `pubdate`, `addition_time`) " .
+ "VALUES (?, ?, ?, 'skipped', ?, ?, ?, ?, ?, ?, ?, ?)";
+ return Dba::write($sql, array($title, $guid, $this->id, $source, $website, $description, $author, $category, $time, $pubdate, time()));
+ } else {
+ debug_log('podcast', 'Episode published before ' . $afterdate . ', skipped', 5);
+ return true;
+ }
+ }
+
+ private function update_lastsync($time)
+ {
+ $sql = "UPDATE `podcast` SET `lastsync` = ? WHERE `id` = ?";
+ return Dba::write($sql, array($time, $this->id));
+ }
+
+ public function sync_episodes($gather=false)
+ {
+ debug_event('podcast', 'Syncing feed ' . $this->feed . ' ...', 5);
+
+ $xmlstr = file_get_contents($this->feed);
+ if ($xmlstr === false) {
+ debug_event('podcast', 'Cannot access feed ' . $this->feed, 1);
+ return false;
+ }
+ $xml = simplexml_load_string($xmlstr);
+ if ($xml === false) {
+ debug_event('podcast', 'Cannot read feed ' . $this->feed, 1);
+ return false;
+ }
+
+ $this->add_episodes($xml->item, $this->lastsync, $gather);
+
+ return true;
+ }
+
+ public function remove()
+ {
+ $episodes = $this->get_episodes();
+ foreach ($episodes as $episode_id) {
+ $episode = new Podcast_Episode($episode_id);
+ $episode->remove();
+ }
+
+ $sql = "DELETE FROM `podcast` WHERE `id` = ?";
+ return Dba::write($sql, array($this->id));
+ }
+
+ public function get_root_path()
+ {
+ $catalog = Catalog::create_from_id($this->catalog);
+ if (!$catalog->get_type() == 'local') {
+ debug_event('podcast', 'Bad catalog type.', 1);
+ return '';
+ }
+
+ $dirname = $this->title;
+ return $catalog->path . DIRECTORY_SEPARATOR . $dirname;
+ }
+}
diff --git a/sources/lib/class/podcast_episode.class.php b/sources/lib/class/podcast_episode.class.php
new file mode 100644
index 0000000..643f4ec
--- /dev/null
+++ b/sources/lib/class/podcast_episode.class.php
@@ -0,0 +1,415 @@
+.
+ *
+ */
+
+class Podcast_Episode extends database_object implements media, library_item
+{
+ public $id;
+ public $title;
+ public $guid;
+ public $podcast;
+ public $state;
+ public $file;
+ public $source;
+ public $size;
+ public $time;
+ public $website;
+ public $description;
+ public $author;
+ public $category;
+ public $pubdate;
+
+ public $catalog;
+ public $f_title;
+ public $f_file;
+ public $f_size;
+ public $f_time;
+ public $f_time_h;
+ public $f_description;
+ public $f_author;
+ public $f_category;
+ public $f_website;
+ public $f_pubdate;
+ public $f_state;
+ public $link;
+ public $f_link;
+ public $f_podcast;
+ public $f_podcast_link;
+
+ /**
+ * Constructor
+ *
+ * Podcast Episode class
+ * @param int|null $id
+ */
+ public function __construct($id = null)
+ {
+ if (!$id) {
+ return false;
+ }
+
+ $this->id = intval($id);
+
+ if ($info = $this->get_info($this->id)) {
+ foreach ($info as $key => $value) {
+ $this->$key = $value;
+ }
+ if (!empty($this->file)) {
+ $data = pathinfo($this->file);
+ $this->type = strtolower($data['extension']);
+ $this->mime = Song::type_to_mime($this->type);
+ }
+ } else {
+ $this->id = null;
+ return false;
+ }
+
+ return true;
+ } // constructor
+
+ /**
+ * gc
+ *
+ * Cleans up the podcast_episode table
+ */
+ public static function gc()
+ {
+ Dba::write('DELETE FROM `podcast_episode` USING `podcast_episode` LEFT JOIN `podcast` ON `podcast`.`id` = `podcast_episode`.`podcast` WHERE `podcast`.`id` IS NULL');
+ }
+
+ /**
+ * get_catalogs
+ *
+ * Get all catalog ids related to this item.
+ * @return int[]
+ */
+ public function get_catalogs()
+ {
+ return array($this->catalog);
+ }
+
+ /**
+ * format
+ * this function takes the object and reformats some values
+ */
+ public function format($details = true)
+ {
+ $this->f_title = scrub_out($this->title);
+ $this->f_description = scrub_out($this->description);
+ $this->f_category = scrub_out($this->category);
+ $this->f_author = scrub_out($this->author);
+ $this->f_website = scrub_out($this->website);
+ $this->f_pubdate = date("m\/d\/Y - H:i", $this->pubdate);
+ $this->f_state = ucfirst($this->state);
+
+ // Format the Time
+ $min = floor($this->time/60);
+ $sec = sprintf("%02d", ($this->time%60));
+ $this->f_time = $min . ":" . $sec;
+ $hour = sprintf("%02d", floor($min/60));
+ $min_h = sprintf("%02d", ($min%60));
+ $this->f_time_h = $hour . ":" . $min_h . ":" . $sec;
+ // Format the Size
+ $this->f_size = UI::format_bytes($this->size);
+ $this->f_file = $this->f_title . '.' . $this->type;
+
+ $this->link = AmpConfig::get('web_path') . '/podcast_episode.php?action=show&podcast_episode=' . $this->id;
+ $this->f_link = '' . $this->f_title . '';
+
+ if ($details) {
+ $podcast = new Podcast($this->podcast);
+ $podcast->format();
+ $this->catalog = $podcast->catalog;
+ $this->f_podcast = $podcast->f_title;
+ $this->f_podcast_link = $podcast->f_link;
+ $this->f_file = $this->f_podcast . ' - ' . $this->f_file;
+ }
+
+ return true;
+ }
+
+ public function get_keywords()
+ {
+ $keywords = array();
+ $keywords['podcast'] = array('important' => true,
+ 'label' => T_('Podcast'),
+ 'value' => $this->f_podcast);
+ $keywords['title'] = array('important' => true,
+ 'label' => T_('Title'),
+ 'value' => $this->f_title);
+
+ return $keywords;
+ }
+
+ public function get_fullname()
+ {
+ return $this->f_title;
+ }
+
+ public function get_parent()
+ {
+ return array('object_type' => 'podcast', 'object_id' => $this->podcast);
+ }
+
+ public function get_childrens()
+ {
+ return array();
+ }
+
+ public function search_childrens($name)
+ {
+ return array();
+ }
+
+ public function get_medias($filter_type = null)
+ {
+ $medias = array();
+ if (!$filter_type || $filter_type == 'podcast_episode') {
+ $medias[] = array(
+ 'object_type' => 'podcast_episode',
+ 'object_id' => $this->id
+ );
+ }
+ return $medias;
+ }
+
+ public function get_user_owner()
+ {
+ return null;
+ }
+
+ public function get_default_art_kind()
+ {
+ return 'default';
+ }
+
+ public function get_description()
+ {
+ return $this->f_description;
+ }
+
+ public function display_art($thumb = 2)
+ {
+ $id = null;
+ $type = null;
+
+ if (Art::has_db($this->id, 'podcast_episode')) {
+ $id = $this->id;
+ $type = 'podcast_episode';
+ } else {
+ if (Art::has_db($this->podcast, 'podcast')) {
+ $id = $this->podcast;
+ $type = 'podcast';
+ }
+ }
+
+ if ($id !== null && $type !== null) {
+ Art::display($type, $id, $this->get_fullname(), $thumb, $this->link);
+ }
+ }
+
+ /**
+ * update
+ * This takes a key'd array of data and updates the current podcast episode
+ */
+ public function update(array $data)
+ {
+ $title = isset($data['title']) ? $data['title'] : $this->title;
+ $website = isset($data['website']) ? $data['website'] : $this->website;
+ $description = isset($data['description']) ? $data['description'] : $this->description;
+ $author = isset($data['author']) ? $data['author'] : $this->author;
+ $category = isset($data['category']) ? $data['category'] : $this->category;
+
+ $sql = 'UPDATE `podcast_episode` SET `title` = ?, `website` = ?, `description` = ?, `author` = ?, `category` = ? WHERE `id` = ?';
+ Dba::write($sql, array($title, $website, $description, $author, $category, $this->id));
+
+ $this->title = $title;
+ $this->website = $website;
+ $this->description = $description;
+ $this->author = $author;
+ $this->category = $category;
+
+ return $this->id;
+ }
+
+ /**
+ * set_played
+ * this checks to see if the current object has been played
+ * if not then it sets it to played. In any case it updates stats.
+ * @param int $user
+ * @param string $agent
+ * @param array $location
+ * @return boolean
+ */
+ public function set_played($user, $agent, $location)
+ {
+ Stats::insert('podcast', $this->podcast, $user, $agent, $location);
+ Stats::insert('podcast_episode', $this->id, $user, $agent, $location);
+
+ if ($this->played) {
+ return true;
+ }
+
+ /* If it hasn't been played, set it! */
+ Podcast_Episode::update_played(true, $this->id);
+
+ return true;
+ } // set_played
+
+ /**
+ * update_played
+ * sets the played flag
+ * @param boolean $new_played
+ * @param int $id
+ */
+ public static function update_played($new_played, $id)
+ {
+ self::_update_item('played', ($new_played ? 1 : 0),$id,'25');
+ } // update_played
+
+ /**
+ * _update_item
+ * This is a private function that should only be called from within the podcast episode class.
+ * It takes a field, value video id and level. first and foremost it checks the level
+ * 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
+ * @param string $field
+ * @param mixed $value
+ * @param int $song_id
+ * @param int $level
+ * @return boolean
+ */
+ private static function _update_item($field, $value, $song_id, $level)
+ {
+ /* Check them Rights! */
+ if (!Access::check('interface',$level)) {
+ return false;
+ }
+
+ /* Can't update to blank */
+ if (!strlen(trim($value))) {
+ return false;
+ }
+
+ $sql = "UPDATE `podcast_episode` SET `$field` = ? WHERE `id` = ?";
+ Dba::write($sql, array($value, $song_id));
+
+ return true;
+ } // _update_item
+
+ /**
+ * Get stream name.
+ * @return string
+ */
+ public function get_stream_name()
+ {
+ return $this->f_podcast . " - " . $this->f_title;
+ }
+
+ /**
+ * Get transcode settings.
+ * @param string $target
+ * @param array $options
+ * @return array|boolean
+ */
+ public function get_transcode_settings($target = null, $player = null, $options=array())
+ {
+ return Song::get_transcode_settings_for_media($this->type, $target, $player, 'song', $options);
+ }
+
+ /**
+ * play_url
+ * This function takes all the song information and correctly formats a
+ * a stream URL taking into account the downsmapling mojo and everything
+ * else, this is the true function
+ * @param int $oid
+ * @param string $additional_params
+ * @param boolean $local
+ * @return string
+ */
+ public static function play_url($oid, $additional_params='', $player=null, $local=false)
+ {
+ return Song::generic_play_url('podcast_episode', $oid, $additional_params, $player, $local);
+ }
+
+ /**
+ * Get stream types.
+ * @return array
+ */
+ public function get_stream_types($player = null)
+ {
+ return Song::get_stream_types_for_type($this->type, $player);
+ }
+
+ public function remove()
+ {
+ debug_event('podcast_episode', 'Removing podcast episode ' . $this->id, 5);
+
+ if (AmpConfig::get('delete_from_disk') && !empty($this->file)) {
+ if (!unlink($this->file)) {
+ debug_event('podcast_episode', 'Cannot delete file ' . $this->file, 3);
+ }
+ }
+
+ $sql = "DELETE FROM `podcast_episode` WHERE `id` = ?";
+ return Dba::write($sql, array($this->id));
+ }
+
+ public function change_state($state)
+ {
+ $sql = "UPDATE `podcast_episode` SET `state` = ? WHERE `id` = ?";
+ return Dba::write($sql, array($state, $this->id));
+ }
+
+ public function gather()
+ {
+ if (!empty($this->source)) {
+ $podcast = new Podcast($this->podcast);
+ $file = $podcast->get_root_path();
+ if (!empty($file)) {
+ $pinfo = pathinfo($this->source);
+ $file .= DIRECTORY_SEPARATOR . $this->id . '-' . $pinfo['basename'];
+ debug_event('podcast_episode', 'Downloading ' . $this->source . ' to ' . $file . ' ...', 5);
+ if (file_put_contents($file, fopen($this->source, 'r')) !== false) {
+ debug_event('podcast_episode', 'Download completed.', 5);
+ $this->file = $file;
+
+ $vainfo = new vainfo($this->file);
+ $vainfo->get_info();
+ $key = vainfo::get_tag_type($vainfo->tags);
+ $infos = vainfo::clean_tag_info($vainfo->tags, $key, $file);
+ // No time information, get it from file
+ if ($this->time <= 0) {
+ $this->time = $infos['time'];
+ }
+ $this->size = $infos['size'];
+
+ $sql = "UPDATE `podcast_episode` SET `file` = ?, `size` = ?, `time` = ?, `state` = 'completed' WHERE `id` = ?";
+ Dba::write($sql, array($this->file, $this->size, $this->time, $this->id));
+ } else {
+ debug_event('podcast_episode', 'Error when downloading podcast episode.', 1);
+ }
+ }
+ } else {
+ debug_event('podcast_episode', 'Cannot download podcast episode ' . $this->id . ', empty source.', 3);
+ }
+ }
+}
diff --git a/sources/lib/class/preference.class.php b/sources/lib/class/preference.class.php
index 70e2ab6..29b4248 100644
--- a/sources/lib/class/preference.class.php
+++ b/sources/lib/class/preference.class.php
@@ -2,22 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; version 2
- * of the License.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -45,18 +44,18 @@ class Preference extends database_object
public static function get_by_user($user_id, $pref_name)
{
//debug_event('preference.class.php', 'Getting preference {'.$pref_name.'} for user identifier {'.$user_id.'}...', '5');
- $user_id = Dba::escape($user_id);
+ $user_id = Dba::escape($user_id);
$pref_name = Dba::escape($pref_name);
- $id = self::id_from_name($pref_name);
+ $id = self::id_from_name($pref_name);
if (parent::is_cached('get_by_user', $user_id)) {
return parent::get_from_cache('get_by_user', $user_id);
}
- $sql = "SELECT `value` FROM `user_preference` WHERE `preference`='$id' AND `user`='$user_id'";
+ $sql = "SELECT `value` FROM `user_preference` WHERE `preference`='$id' AND `user`='$user_id'";
$db_results = Dba::read($sql);
if (Dba::num_rows($db_results) < 1) {
- $sql = "SELECT `value` FROM `user_preference` WHERE `preference`='$id' AND `user`='-1'";
+ $sql = "SELECT `value` FROM `user_preference` WHERE `preference`='$id' AND `user`='-1'";
$db_results = Dba::read($sql);
}
$data = Dba::fetch_assoc($db_results);
@@ -75,19 +74,23 @@ class Preference extends database_object
{
// First prepare
if (!is_numeric($preference)) {
- $id = self::id_from_name($preference);
+ $id = self::id_from_name($preference);
$name = $preference;
} else {
$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 = "";
} else {
$user_check = " AND `user`='$user_id'";
}
- if ($applytodefault AND Access::check('interface', '100')) {
+ if (is_array($value)) {
+ $value = implode(',', $value);
+ }
+
+ if ($applytodefault and Access::check('interface', '100')) {
$sql = "UPDATE `preference` SET `value`='$value' WHERE `id`='$id'";
Dba::write($sql);
}
@@ -96,7 +99,7 @@ class Preference extends database_object
if (self::has_access($name)) {
$user_id = Dba::escape($user_id);
- $sql = "UPDATE `user_preference` SET `value`='$value' WHERE `preference`='$id'$user_check";
+ $sql = "UPDATE `user_preference` SET `value`='$value' WHERE `preference`='$id'$user_check";
Dba::write($sql);
Preference::clear_from_session();
@@ -124,7 +127,7 @@ class Preference extends database_object
}
$preference_id = Dba::escape($preference_id);
- $level = Dba::escape($level);
+ $level = Dba::escape($level);
$sql = "UPDATE `preference` SET `level`='$level' WHERE `id`='$preference_id'";
Dba::write($sql);
@@ -139,7 +142,7 @@ class Preference extends database_object
public static function update_all($preference_id,$value)
{
$preference_id = Dba::escape($preference_id);
- $value = Dba::escape($value);
+ $value = Dba::escape($value);
$sql = "UPDATE `user_preference` SET `value`='$value' WHERE `preference`='$preference_id'";
Dba::write($sql);
@@ -156,8 +159,8 @@ class Preference extends database_object
public static function exists($preference)
{
// We assume it's the name
- $name = Dba::escape($preference);
- $sql = "SELECT * FROM `preference` WHERE `name`='$name'";
+ $name = Dba::escape($preference);
+ $sql = "SELECT * FROM `preference` WHERE `name`='$name'";
$db_results = Dba::read($sql);
return Dba::num_rows($db_results);
@@ -177,9 +180,9 @@ class Preference extends database_object
$preference = Dba::escape($preference);
- $sql = "SELECT `level` FROM `preference` WHERE `name`='$preference'";
+ $sql = "SELECT `level` FROM `preference` WHERE `name`='$preference'";
$db_results = Dba::read($sql);
- $data = Dba::fetch_assoc($db_results);
+ $data = Dba::fetch_assoc($db_results);
if (Access::check('interface',$data['level'])) {
return true;
@@ -200,9 +203,9 @@ class Preference extends database_object
return parent::get_from_cache('id_from_name', $name);
}
- $sql = "SELECT `id` FROM `preference` WHERE `name`='$name'";
+ $sql = "SELECT `id` FROM `preference` WHERE `name`='$name'";
$db_results = Dba::read($sql);
- $row = Dba::fetch_assoc($db_results);
+ $row = Dba::fetch_assoc($db_results);
parent::add_to_cache('id_from_name', $name, $row['id']);
@@ -218,7 +221,7 @@ class Preference extends database_object
{
$id = Dba::escape($id);
- $sql = "SELECT `name` FROM `preference` WHERE `id`='$id'";
+ $sql = "SELECT `name` FROM `preference` WHERE `id`='$id'";
$db_results = Dba::read($sql);
$row = Dba::fetch_assoc($db_results);
@@ -233,7 +236,7 @@ class Preference extends database_object
*/
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);
$results = array();
@@ -260,16 +263,16 @@ class Preference extends database_object
$user_limit = "AND `preference`.`catagory` != 'system'";
}
- $sql = "SELECT `preference`.`name`,`preference`.`description`,`user_preference`.`value` FROM `preference` " .
+ $sql = "SELECT `preference`.`name`,`preference`.`description`,`preference`.`subcatagory`,`user_preference`.`value` FROM `preference` " .
" INNER JOIN `user_preference` ON `user_preference`.`preference`=`preference`.`id` " .
" WHERE `user_preference`.`user`='$user_id' AND `preference`.`catagory` != 'internal' $user_limit " .
- " ORDER BY `preference`.`description`";
+ " ORDER BY `preference`.`subcatagory`,`preference`.`description`";
$db_results = Dba::read($sql);
- $results = array();
+ $results = array();
while ($row = Dba::fetch_assoc($db_results)) {
- $results[] = array('name'=>$row['name'],'level'=>$row['level'],'description'=>$row['description'],'value'=>$row['value']);
+ $results[] = array('name'=>$row['name'],'level'=>$row['level'],'description'=>$row['description'],'value'=>$row['value'],'subcategory'=>$row['subcatagory']);
}
return $results;
@@ -280,26 +283,31 @@ class Preference extends database_object
* This inserts a new preference into the preference table
* it does NOT sync up the users, that should be done independently
*/
- public static function insert($name,$description,$default,$level,$type,$catagory)
+ public static function insert($name,$description,$default,$level,$type,$catagory,$subcatagory=null)
{
- $sql = "INSERT INTO `preference` (`name`,`description`,`value`,`level`,`type`,`catagory`) " .
- "VALUES (?, ?, ?, ?, ?, ?)";
- $db_results = Dba::write($sql, array($name, $description, $default, intval($level), $type, $catagory));
+ if ($subcatagory !== null) {
+ $subcatagory = strtolower($subcatagory);
+ }
+ $sql = "INSERT INTO `preference` (`name`,`description`,`value`,`level`,`type`,`catagory`,`subcatagory`) " .
+ "VALUES (?, ?, ?, ?, ?, ?, ?)";
+ $db_results = Dba::write($sql, array($name, $description, $default, intval($level), $type, $catagory, $subcatagory));
if (!$db_results) {
return false;
}
- $id = Dba::insert_id();
- $params = array($id, $default);
- $sql = "INSERT INTO `user_preference` VALUES (-1,?,?)";
+ $id = Dba::insert_id();
+ $params = array($id, $default);
+ $sql = "INSERT INTO `user_preference` VALUES (-1,?,?)";
$db_results = Dba::write($sql, $params);
- if (!$db_results)
+ if (!$db_results) {
return false;
+ }
if ($catagory !== "system") {
- $sql = "INSERT INTO `user_preference` SELECT `user`.`id`, ?, ? FROM `user`";
+ $sql = "INSERT INTO `user_preference` SELECT `user`.`id`, ?, ? FROM `user`";
$db_results = Dba::write($sql, $params);
- if (!$db_results)
+ if (!$db_results) {
return false;
+ }
}
return true;
@@ -384,7 +392,7 @@ class Preference extends database_object
*/
public static function load_from_session($uid=-1)
{
- if (isset($_SESSION['userdata']['preferences']) && is_array($_SESSION['userdata']['preferences']) AND $_SESSION['userdata']['uid'] == $uid) {
+ if (isset($_SESSION['userdata']['preferences']) && is_array($_SESSION['userdata']['preferences']) and $_SESSION['userdata']['uid'] == $uid) {
AmpConfig::set_by_array($_SESSION['userdata']['preferences'], true);
return true;
}
@@ -452,28 +460,47 @@ class Preference extends database_object
$results = array();
while ($row = Dba::fetch_assoc($db_results)) {
- $value = $row['system_value'] ? $row['system_value'] : $row['value'];
- $name = $row['name'];
+ $value = $row['system_value'] ? $row['system_value'] : $row['value'];
+ $name = $row['name'];
$results[$name] = $value;
} // end while sys prefs
/* Set the Theme mojo */
if (strlen($results['theme_name']) > 0) {
- $results['theme_path'] = '/themes/' . $results['theme_name'];
// In case the theme was removed
- if (!Core::is_readable(AmpConfig::get('prefix') . $results['theme_path'])) {
- unset($results['theme_path']);
+ if (!Core::is_readable(AmpConfig::get('prefix') . '/themes/' . $results['theme_name'])) {
+ unset($results['theme_name']);
}
+ } else {
+ unset($results['theme_name']);
}
// Default theme if we don't get anything from their
// preferences because we're going to want at least something otherwise
// the page is going to be really ugly
- if (!isset($results['theme_path'])) {
- $results['theme_path'] = '/themes/reborn';
+ if (!isset($results['theme_name'])) {
+ $results['theme_name'] = 'reborn';
+ }
+ $results['theme_path'] = '/themes/' . $results['theme_name'];
+
+ // Load theme settings
+ $themecfg = get_theme($results['theme_name']);
+ $results['theme_css_base'] = $themecfg['base'];
+
+ if (strlen($results['theme_color']) > 0) {
+ // In case the color was removed
+ if (!Core::is_readable(AmpConfig::get('prefix') . '/themes/' . $results['theme_name'] . '/templates/' . $results['theme_color'] . '.css')) {
+ unset($results['theme_color']);
+ }
+ } else {
+ unset($results['theme_color']);
+ }
+ if (!isset($results['theme_color'])) {
+ $results['theme_color'] = strtolower($themecfg['colors'][0]);
}
AmpConfig::set_by_array($results, true);
$_SESSION['userdata']['preferences'] = $results;
- $_SESSION['userdata']['uid'] = $user_id;
+ $_SESSION['userdata']['uid'] = $user_id;
} // init
} // end Preference class
+
diff --git a/sources/lib/class/privatemsg.class.php b/sources/lib/class/privatemsg.class.php
index 703a4ef..4fee976 100644
--- a/sources/lib/class/privatemsg.class.php
+++ b/sources/lib/class/privatemsg.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -93,7 +93,9 @@ class PrivateMsg extends database_object
*/
public function __construct($id=null)
{
- if (!$id) { return false; }
+ if (!$id) {
+ return false;
+ }
$info = $this->get_info($id, 'user_pvmsg');
foreach ($info as $key=>$value) {
@@ -105,17 +107,17 @@ class PrivateMsg extends database_object
public function format($details = true)
{
- $this->f_subject = scrub_out($this->subject);
- $this->f_message = scrub_out($this->message);
+ $this->f_subject = scrub_out($this->subject);
+ $this->f_message = scrub_out($this->message);
$this->f_creation_date = date("Y/m/d H:i:s", $this->creation_date);
- $from_user = new User($this->from_user);
+ $from_user = new User($this->from_user);
$from_user->format();
$this->f_from_user_link = $from_user->f_link;
- $to_user = new User($this->to_user);
+ $to_user = new User($this->to_user);
$to_user->format();
$this->f_to_user_link = $to_user->f_link;
- $this->link = AmpConfig::get('web_path') . '/pvmsg.php?pvmsg_id=' . $this->id;
- $this->f_link = "link . "\">" . $this->f_subject . "";
+ $this->link = AmpConfig::get('web_path') . '/pvmsg.php?pvmsg_id=' . $this->id;
+ $this->f_link = "link . "\">" . $this->f_subject . "";
}
public function set_is_read($read)
@@ -136,19 +138,19 @@ class PrivateMsg extends database_object
$message = trim(strip_tags($data['message']));
if (empty($subject)) {
- Error::add('subject', T_('Error: Subject Required'));
+ AmpError::add('subject', T_('Error: Subject Required'));
}
$to_user = User::get_from_username($data['to_user']);
if (!$to_user->id) {
- Error::add('to_user', T_('Error: Unknown user'));
+ AmpError::add('to_user', T_('Error: Unknown user'));
}
- if (!Error::occurred()) {
- $from_user = $data['from_user'] ?: $GLOBALS['user']->id;
+ if (!AmpError::occurred()) {
+ $from_user = $data['from_user'] ?: $GLOBALS['user']->id;
$creation_date = $data['creation_date'] ?: time();
- $is_read = $data['is_read'] ?: 0;
- $sql = "INSERT INTO `user_pvmsg` (`subject`, `message`, `from_user`, `to_user`, `creation_date`, `is_read`) " .
+ $is_read = $data['is_read'] ?: 0;
+ $sql = "INSERT INTO `user_pvmsg` (`subject`, `message`, `from_user`, `to_user`, `creation_date`, `is_read`) " .
"VALUES (?, ?, ?, ?, ?, ?)";
if (Dba::write($sql, array($subject, $message, $from_user, $to_user->id, $creation_date, $is_read))) {
$insert_id = Dba::insert_id();
@@ -159,10 +161,10 @@ class PrivateMsg extends database_object
if (!empty($to_user->email)) {
$mailer = new Mailer();
$mailer->set_default_sender();
- $mailer->recipient = $to_user->email;
+ $mailer->recipient = $to_user->email;
$mailer->recipient_name = $to_user->fullname;
- $mailer->subject = "[" . T_('Private Message') . "] " . $subject;
- $mailer->message = sprintf(T_("You just received a new private message from %s.\n\n
+ $mailer->subject = "[" . T_('Private Message') . "] " . $subject;
+ $mailer->message = sprintf(T_("You just received a new private message from %s.\n\n
----------------------
%s
----------------------
@@ -191,7 +193,7 @@ class PrivateMsg extends database_object
*/
public static function get_private_msgs($to_user, $unread_only = false, $from_user = 0)
{
- $sql = "SELECT `id` FROM `user_pvmsg` WHERE `to_user` = ?";
+ $sql = "SELECT `id` FROM `user_pvmsg` WHERE `to_user` = ?";
$params = array($to_user);
if ($unread_only) {
$sql .= " AND `is_read` = '0'";
@@ -202,7 +204,7 @@ class PrivateMsg extends database_object
}
$db_results = Dba::read($sql, $params);
- $results = array();
+ $results = array();
while ($row = Dba::fetch_assoc($db_results)) {
$results[] = $row['id'];
}
diff --git a/sources/lib/class/query.class.php b/sources/lib/class/query.class.php
index 645e499..6225502 100644
--- a/sources/lib/class/query.class.php
+++ b/sources/lib/class/query.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -89,15 +89,14 @@ class Query
$db_results = Dba::read($sql, array($id, $sid));
if ($results = Dba::fetch_assoc($db_results)) {
-
- $this->id = $id;
+ $this->id = $id;
$this->_state = (array) self::_unserialize($results['data']);
return true;
}
}
- Error::add('browse', T_('Browse not found or expired, try reloading the page'));
+ AmpError::add('browse', T_('Browse not found or expired, try reloading the page'));
return false;
}
@@ -231,6 +230,18 @@ class Query
'follower' => array(
'user',
'to_user',
+ ),
+ 'podcast' => array(
+ 'alpha_match',
+ 'regex_match',
+ 'regex_not_match',
+ 'starts_with'
+ ),
+ 'podcast_episode' => array(
+ 'alpha_match',
+ 'regex_match',
+ 'regex_not_match',
+ 'starts_with'
)
);
@@ -239,14 +250,6 @@ class Query
}
self::$allowed_sorts = array(
- 'playlist_song' => array(
- 'title',
- 'year',
- 'track',
- 'time',
- 'album',
- 'artist'
- ),
'song' => array(
'title',
'year',
@@ -393,6 +396,16 @@ class Query
'user',
'follow_user',
'follow_date'
+ ),
+ 'podcast' => array(
+ 'title'
+ ),
+ 'podcast_episode' => array(
+ 'title',
+ 'category',
+ 'author',
+ 'time',
+ 'pubDate'
)
);
@@ -485,14 +498,24 @@ class Query
case 'regex_match':
case 'regex_not_match':
case 'starts_with':
- if ($this->is_static_content()) { return false; }
+ if ($this->is_static_content()) {
+ return false;
+ }
$this->_state['filter'][$key] = $value;
- if ($key == 'regex_match') unset($this->_state['filter']['regex_not_match']);
- if ($key == 'regex_not_match') unset($this->_state['filter']['regex_match']);
+ if ($key == 'regex_match') {
+ unset($this->_state['filter']['regex_not_match']);
+ }
+ if ($key == 'regex_not_match') {
+ unset($this->_state['filter']['regex_match']);
+ }
break;
case 'playlist_type':
// Must be a content manager to turn this off
- if (Access::check('interface','100')) { unset($this->_state['filter'][$key]); } else { $this->_state['filter'][$key] = '1'; }
+ if (Access::check('interface','100')) {
+ unset($this->_state['filter'][$key]);
+ } else {
+ $this->_state['filter'][$key] = '1';
+ }
break;
default:
// Rien a faire
@@ -504,7 +527,6 @@ class Query
$this->set_start(0);
return true;
-
} // set_filter
/**
@@ -524,7 +546,6 @@ class Query
$this->set_is_simple(false);
$this->set_start(0);
$this->set_offset(AmpConfig::get('offset_limit') ? AmpConfig::get('offset_limit') : '25');
-
} // reset
/**
@@ -533,8 +554,7 @@ class Query
*/
public function reset_base()
{
- $this->_state['base'] = NULL;
-
+ $this->_state['base'] = null;
} // reset_base
/**
@@ -544,7 +564,6 @@ class Query
public function reset_select()
{
$this->_state['select'] = array();
-
} // reset_select
/**
@@ -554,7 +573,6 @@ class Query
public function reset_having()
{
unset($this->_state['having']);
-
} // reset_having
/**
@@ -564,7 +582,6 @@ class Query
public function reset_join()
{
unset($this->_state['join']);
-
} // reset_join
/**
@@ -574,7 +591,6 @@ class Query
public function reset_filters()
{
$this->_state['filter'] = array();
-
} // reset_filters
/**
@@ -584,7 +600,6 @@ class Query
public function reset_total()
{
unset($this->_state['total']);
-
} // reset_total
/**
@@ -599,7 +614,6 @@ class Query
return isset($this->_state['filter'][$key])
? $this->_state['filter'][$key]
: false;
-
} // get_filter
/**
@@ -610,7 +624,6 @@ class Query
public function get_start()
{
return $this->_state['start'];
-
} // get_start
/**
@@ -654,12 +667,11 @@ class Query
}
$db_results = Dba::read($this->get_sql(false));
- $num_rows = Dba::num_rows($db_results);
+ $num_rows = Dba::num_rows($db_results);
$this->_state['total'] = $num_rows;
return $num_rows;
-
} // get_total
/**
@@ -691,7 +703,7 @@ class Query
case 'user':
case 'video':
case 'playlist':
- case 'playlist_song':
+ case 'playlist_media':
case 'smartplaylist':
case 'song':
case 'catalog':
@@ -717,6 +729,8 @@ class Query
case 'label':
case 'pvmsg':
case 'follower':
+ case 'podcast':
+ case 'podcast_episode':
// Set it
$this->_state['type'] = $type;
$this->set_base_sql(true, $custom_base);
@@ -735,7 +749,6 @@ class Query
public function get_type()
{
return $this->_state['type'];
-
} // get_type
/**
@@ -754,21 +767,20 @@ class Query
$this->reset_join();
if ($order) {
- $order = ($order == 'DESC') ? 'DESC' : 'ASC';
- $this->_state['sort'] = array();
+ $order = ($order == 'DESC') ? 'DESC' : 'ASC';
+ $this->_state['sort'] = array();
$this->_state['sort'][$sort] = $order;
} elseif ($this->_state['sort'][$sort] == 'DESC') {
// 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';
} else {
// 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->resort_objects();
-
} // set_sort
/**
@@ -779,7 +791,6 @@ class Query
public function set_offset($offset)
{
$this->_state['offset'] = abs($offset);
-
} // set_offset
/**
@@ -802,7 +813,6 @@ class Query
public function set_select($field)
{
$this->_state['select'][] = $field;
-
} // set_select
/**
@@ -817,7 +827,6 @@ class Query
public function set_join($type, $table, $source, $dest, $priority)
{
$this->_state['join'][$priority][$table] = strtoupper($type) . ' JOIN ' . $table . ' ON ' . $source . '=' . $dest;
-
} // set_join
/**
@@ -829,7 +838,6 @@ class Query
public function set_having($condition)
{
$this->_state['having'] = $condition;
-
} // set_having
/**
@@ -841,7 +849,7 @@ class Query
*/
public function set_start($start)
{
- $start = intval($start);
+ $start = intval($start);
$this->_state['start'] = $start;
} // set_start
@@ -853,9 +861,8 @@ class Query
*/
public function set_is_simple($value)
{
- $value = make_bool($value);
+ $value = make_bool($value);
$this->_state['simple'] = $value;
-
} // set_is_simple
/**
@@ -870,7 +877,6 @@ class Query
$value = make_bool($value);
$this->_state['static'] = $value;
-
} // set_static_content
/**
@@ -890,7 +896,6 @@ class Query
public function is_simple()
{
return $this->_state['simple'];
-
} // is_simple
/**
@@ -920,7 +925,6 @@ class Query
}
return $objects;
-
} // get_saved
/**
@@ -934,7 +938,7 @@ class Query
{
// First we need to get the SQL statement we are going to run
// This has to run against any possible filters (dependent on type)
- $sql = $this->get_sql(true);
+ $sql = $this->get_sql(true);
$db_results = Dba::read($sql);
$results = array();
@@ -942,7 +946,7 @@ class Query
$results[] = $data;
}
- $results = $this->post_process($results);
+ $results = $this->post_process($results);
$filtered = array();
foreach ($results as $data) {
// Make sure that this object passes the logic filter
@@ -955,7 +959,6 @@ class Query
$this->save_objects($filtered);
return $filtered;
-
} // get_objects
/**
@@ -967,16 +970,18 @@ class Query
private function set_base_sql($force = false, $custom_base = '')
{
// Only allow it to be set once
- if (strlen($this->_state['base']) && !$force) { return true; }
+ if (strlen($this->_state['base']) && !$force) {
+ return true;
+ }
// Custom sql base
if ($force && !empty($custom_base)) {
$this->_state['custom'] = true;
- $sql = $custom_base;
+ $sql = $custom_base;
} else {
switch ($this->get_type()) {
case 'album':
- $this->set_select("DISTINCT(`album`.`id`)");
+ $this->set_select("`album`.`id`");
$sql = "SELECT %%SELECT%% FROM `album` ";
break;
case 'artist':
@@ -1012,24 +1017,24 @@ class Query
$sql = "SELECT %%SELECT%% FROM `video` ";
break;
case 'tag':
- $this->set_select("DISTINCT(`tag`.`id`)");
+ $this->set_select("`tag`.`id`");
$this->set_join('left', 'tag_map', '`tag_map`.`tag_id`', '`tag`.`id`', 1);
$sql = "SELECT %%SELECT%% FROM `tag` ";
break;
case 'wanted':
- $this->set_select("DISTINCT(`wanted`.`id`)");
+ $this->set_select("`wanted`.`id`");
$sql = "SELECT %%SELECT%% FROM `wanted` ";
break;
case 'share':
- $this->set_select("DISTINCT(`share`.`id`)");
+ $this->set_select("`share`.`id`");
$sql = "SELECT %%SELECT%% FROM `share` ";
break;
case 'channel':
- $this->set_select("DISTINCT(`channel`.`id`)");
+ $this->set_select("`channel`.`id`");
$sql = "SELECT %%SELECT%% FROM `channel` ";
break;
case 'broadcast':
- $this->set_select("DISTINCT(`broadcast`.`id`)");
+ $this->set_select("`broadcast`.`id`");
$sql = "SELECT %%SELECT%% FROM `broadcast` ";
break;
case 'license':
@@ -1072,10 +1077,19 @@ class Query
$this->set_select("`user_follower`.`id`");
$sql = "SELECT %%SELECT%% FROM `user_follower` ";
break;
- case 'playlist_song':
+ case 'podcast':
+ $this->set_select("`podcast`.`id`");
+ $sql = "SELECT %%SELECT%% FROM `podcast` ";
+ break;
+ case 'podcast_episode':
+ $this->set_select("`podcast_episode`.`id`");
+ $sql = "SELECT %%SELECT%% FROM `podcast_episode` ";
+ break;
+ case 'playlist_media':
+ break;
case 'song':
default:
- $this->set_select("DISTINCT(`song`.`id`)");
+ $this->set_select("`song`.`id`");
$sql = "SELECT %%SELECT%% FROM `song` ";
break;
} // end base sql
@@ -1094,7 +1108,6 @@ class Query
{
$select_string = implode(", ", $this->_state['select']);
return $select_string;
-
} // get_select
/**
@@ -1107,7 +1120,6 @@ class Query
{
$sql = str_replace("%%SELECT%%", $this->get_select(), $this->_state['base']);
return $sql;
-
} // get_base_sql
/**
@@ -1125,7 +1137,6 @@ class Query
foreach ($this->_state['filter']
as $key => $value) {
-
$sql .= $this->sql_filter($key, $value);
}
@@ -1149,7 +1160,6 @@ class Query
$sql = rtrim($sql,'AND ') . ' ';
return $sql;
-
} // get_filter_sql
/**
@@ -1174,7 +1184,6 @@ class Query
$sql = rtrim($sql,',');
return $sql;
-
} // get_sort_sql
/**
@@ -1184,12 +1193,13 @@ class Query
*/
private function get_limit_sql()
{
- if (!$this->is_simple() || $this->get_start() < 0) { return ''; }
+ if (!$this->is_simple() || $this->get_start() < 0) {
+ return '';
+ }
$sql = ' LIMIT ' . intval($this->get_start()) . ',' . intval($this->get_offset());
return $sql;
-
} // get_limit_sql
/**
@@ -1212,7 +1222,6 @@ class Query
} // end foreach of this level of joins
return $sql;
-
} // get_join_sql
/**
@@ -1225,7 +1234,6 @@ class Query
$sql = isset($this->_state['having']) ? $this->_state['having'] : '';
return $sql;
-
} // get_having_sql
/**
@@ -1241,25 +1249,24 @@ class Query
$sql = $this->get_base_sql();
$filter_sql = "";
- $join_sql = "";
+ $join_sql = "";
$having_sql = "";
- $order_sql = "";
+ $order_sql = "";
if (!isset($this->_state['custom']) || !$this->_state['custom']) {
$filter_sql = $this->get_filter_sql();
- $order_sql = $this->get_sort_sql();
- $join_sql = $this->get_join_sql();
+ $order_sql = $this->get_sort_sql();
+ $join_sql = $this->get_join_sql();
$having_sql = $this->get_having_sql();
}
$limit_sql = $limit ? $this->get_limit_sql() : '';
$final_sql = $sql . $join_sql . $filter_sql . $having_sql;
if ( $this->get_type() == 'artist' && !$this->_state['custom'] ) {
- $final_sql .= " GROUP BY `" . $this->get_type() . "`.`name` ";
+ $final_sql .= " GROUP BY `" . $this->get_type() . "`.`name`, `" . $this->get_type() . "`.`id` ";
}
$final_sql .= $order_sql . $limit_sql;
return $final_sql;
-
} // get_sql
/**
@@ -1278,7 +1285,7 @@ class Query
}
$tag_count = sizeof($tags);
- $count = array();
+ $count = array();
foreach ($data as $row) {
$count[$row['id']]++;
@@ -1293,7 +1300,6 @@ class Query
} // end foreach
return $results;
-
} // post_process
/**
@@ -1328,10 +1334,14 @@ class Query
$filter_sql = " `song`.`title` LIKE '%" . Dba::escape($value) . "%' AND ";
break;
case 'regex_match':
- if (!empty($value)) $filter_sql = " `song`.`title` REGEXP '" . Dba::escape($value) . "' AND ";
+ if (!empty($value)) {
+ $filter_sql = " `song`.`title` REGEXP '" . Dba::escape($value) . "' AND ";
+ }
break;
case 'regex_not_match':
- if (!empty($value)) $filter_sql = " `song`.`title` NOT REGEXP '" . Dba::escape($value) . "' AND ";
+ if (!empty($value)) {
+ $filter_sql = " `song`.`title` NOT REGEXP '" . Dba::escape($value) . "' AND ";
+ }
break;
case 'starts_with':
$filter_sql = " `song`.`title` LIKE '" . Dba::escape($value) . "%' AND ";
@@ -1343,10 +1353,10 @@ class Query
$filter_sql = " `song`.`played`='0' AND ";
break;
case 'album':
- $filter_sql = " `song`.`album` = '". Dba::escape($value) . "' AND ";
+ $filter_sql = " `song`.`album` = '" . Dba::escape($value) . "' AND ";
break;
case 'artist':
- $filter_sql = " `song`.`artist` = '". Dba::escape($value) . "' AND ";
+ $filter_sql = " `song`.`artist` = '" . Dba::escape($value) . "' AND ";
break;
case 'add_gt':
$filter_sql = " `song`.`addition_time` >= '" . Dba::escape($value) . "' AND ";
@@ -1392,10 +1402,14 @@ class Query
$filter_sql = " `album`.`name` LIKE '%" . Dba::escape($value) . "%' AND ";
break;
case 'regex_match':
- if (!empty($value)) $filter_sql = " `album`.`name` REGEXP '" . Dba::escape($value) . "' AND ";
+ if (!empty($value)) {
+ $filter_sql = " `album`.`name` REGEXP '" . Dba::escape($value) . "' AND ";
+ }
break;
case 'regex_not_match':
- if (!empty($value)) $filter_sql = " `album`.`name` NOT REGEXP '" . Dba::escape($value) . "' AND ";
+ if (!empty($value)) {
+ $filter_sql = " `album`.`name` NOT REGEXP '" . Dba::escape($value) . "' AND ";
+ }
break;
case 'starts_with':
$this->set_join('left', '`song`', '`album`.`id`', '`song`.`album`', 100);
@@ -1405,7 +1419,7 @@ class Query
}
break;
case 'artist':
- $filter_sql = " `artist`.`id` = '". Dba::escape($value) . "' AND ";
+ $filter_sql = " `artist`.`id` = '" . Dba::escape($value) . "' AND ";
break;
case 'add_lt':
$this->set_join('left', '`song`', '`song`.`album`', '`album`.`id`', 100);
@@ -1465,10 +1479,14 @@ class Query
$filter_sql = " `artist`.`name` LIKE '%" . Dba::escape($value) . "%' AND ";
break;
case 'regex_match':
- if (!empty($value)) $filter_sql = " `artist`.`name` REGEXP '" . Dba::escape($value) . "' AND ";
+ if (!empty($value)) {
+ $filter_sql = " `artist`.`name` REGEXP '" . Dba::escape($value) . "' AND ";
+ }
break;
case 'regex_not_match':
- if (!empty($value)) $filter_sql = " `artist`.`name` NOT REGEXP '" . Dba::escape($value) . "' AND ";
+ if (!empty($value)) {
+ $filter_sql = " `artist`.`name` NOT REGEXP '" . Dba::escape($value) . "' AND ";
+ }
break;
case 'starts_with':
$this->set_join('left', '`song`', '`artist`.`id`', '`song`.`artist`', 100);
@@ -1509,10 +1527,14 @@ class Query
$filter_sql = " `live_stream`.`name` LIKE '%" . Dba::escape($value) . "%' AND ";
break;
case 'regex_match':
- if (!empty($value)) $filter_sql = " `live_stream`.`name` REGEXP '" . Dba::escape($value) . "' AND ";
+ if (!empty($value)) {
+ $filter_sql = " `live_stream`.`name` REGEXP '" . Dba::escape($value) . "' AND ";
+ }
break;
case 'regex_not_match':
- if (!empty($value)) $filter_sql = " `live_stream`.`name` NOT REGEXP '" . Dba::escape($value) . "' AND ";
+ if (!empty($value)) {
+ $filter_sql = " `live_stream`.`name` NOT REGEXP '" . Dba::escape($value) . "' AND ";
+ }
break;
case 'starts_with':
$filter_sql = " `live_stream`.`name` LIKE '" . Dba::escape($value) . "%' AND ";
@@ -1532,16 +1554,20 @@ class Query
$filter_sql = " `playlist`.`name` LIKE '%" . Dba::escape($value) . "%' AND ";
break;
case 'regex_match':
- if (!empty($value)) $filter_sql = " `playlist`.`name` REGEXP '" . Dba::escape($value) . "' AND ";
+ if (!empty($value)) {
+ $filter_sql = " `playlist`.`name` REGEXP '" . Dba::escape($value) . "' AND ";
+ }
break;
case 'regex_not_match':
- if (!empty($value)) $filter_sql = " `playlist`.`name` NOT REGEXP '" . Dba::escape($value) . "' AND ";
+ if (!empty($value)) {
+ $filter_sql = " `playlist`.`name` NOT REGEXP '" . Dba::escape($value) . "' AND ";
+ }
break;
case 'starts_with':
$filter_sql = " `playlist`.`name` LIKE '" . Dba::escape($value) . "%' AND ";
break;
case 'playlist_type':
- $user_id = intval($GLOBALS['user']->id);
+ $user_id = intval($GLOBALS['user']->id);
$filter_sql = " (`playlist`.`type` = 'public' OR `playlist`.`user`='$user_id') AND ";
break;
default;
@@ -1555,16 +1581,20 @@ class Query
$filter_sql = " `search`.`name` LIKE '%" . Dba::escape($value) . "%' AND ";
break;
case 'regex_match':
- if (!empty($value)) $filter_sql = " `search`.`name` REGEXP '" . Dba::escape($value) . "' AND ";
+ if (!empty($value)) {
+ $filter_sql = " `search`.`name` REGEXP '" . Dba::escape($value) . "' AND ";
+ }
break;
case 'regex_not_match':
- if (!empty($value)) $filter_sql = " `search`.`name` NOT REGEXP '" . Dba::escape($value) . "' AND ";
+ if (!empty($value)) {
+ $filter_sql = " `search`.`name` NOT REGEXP '" . Dba::escape($value) . "' AND ";
+ }
break;
case 'starts_with':
$filter_sql = " `search`.`name` LIKE '" . Dba::escape($value) . "%' AND ";
break;
case 'playlist_type':
- $user_id = intval($GLOBALS['user']->id);
+ $user_id = intval($GLOBALS['user']->id);
$filter_sql = " (`search`.`type` = 'public' OR `search`.`user`='$user_id') AND ";
break;
} // end switch on $filter
@@ -1575,10 +1605,14 @@ class Query
$filter_sql = " `tag`.`name` LIKE '%" . Dba::escape($value) . "%' AND ";
break;
case 'regex_match':
- if (!empty($value)) $filter_sql = " `tag`.`name` REGEXP '" . Dba::escape($value) . "' AND ";
+ if (!empty($value)) {
+ $filter_sql = " `tag`.`name` REGEXP '" . Dba::escape($value) . "' AND ";
+ }
break;
case 'regex_not_match':
- if (!empty($value)) $filter_sql = " `tag`.`name` NOT REGEXP '" . Dba::escape($value) . "' AND ";
+ if (!empty($value)) {
+ $filter_sql = " `tag`.`name` NOT REGEXP '" . Dba::escape($value) . "' AND ";
+ }
break;
case 'exact_match':
$filter_sql = " `tag`.`name` = '" . Dba::escape($value) . "' AND ";
@@ -1606,10 +1640,14 @@ class Query
$filter_sql = " `video`.`title` LIKE '%" . Dba::escape($value) . "%' AND ";
break;
case 'regex_match':
- if (!empty($value)) $filter_sql = " `video`.`title` REGEXP '" . Dba::escape($value) . "' AND ";
+ if (!empty($value)) {
+ $filter_sql = " `video`.`title` REGEXP '" . Dba::escape($value) . "' AND ";
+ }
break;
case 'regex_not_match':
- if (!empty($value)) $filter_sql = " `video`.`title` NOT REGEXP '" . Dba::escape($value) . "' AND ";
+ if (!empty($value)) {
+ $filter_sql = " `video`.`title` NOT REGEXP '" . Dba::escape($value) . "' AND ";
+ }
break;
case 'starts_with':
$filter_sql = " `video`.`title` LIKE '" . Dba::escape($value) . "%' AND ";
@@ -1625,10 +1663,14 @@ class Query
$filter_sql = " `license`.`name` LIKE '%" . Dba::escape($value) . "%' AND ";
break;
case 'regex_match':
- if (!empty($value)) $filter_sql = " `license`.`name` REGEXP '" . Dba::escape($value) . "' AND ";
+ if (!empty($value)) {
+ $filter_sql = " `license`.`name` REGEXP '" . Dba::escape($value) . "' AND ";
+ }
break;
case 'regex_not_match':
- if (!empty($value)) $filter_sql = " `license`.`name` NOT REGEXP '" . Dba::escape($value) . "' AND ";
+ if (!empty($value)) {
+ $filter_sql = " `license`.`name` NOT REGEXP '" . Dba::escape($value) . "' AND ";
+ }
break;
case 'exact_match':
$filter_sql = " `license`.`name` = '" . Dba::escape($value) . "' AND ";
@@ -1644,10 +1686,14 @@ class Query
$filter_sql = " `tvshow`.`name` LIKE '%" . Dba::escape($value) . "%' AND ";
break;
case 'regex_match':
- if (!empty($value)) $filter_sql = " `tvshow`.`name` REGEXP '" . Dba::escape($value) . "' AND ";
+ if (!empty($value)) {
+ $filter_sql = " `tvshow`.`name` REGEXP '" . Dba::escape($value) . "' AND ";
+ }
break;
case 'regex_not_match':
- if (!empty($value)) $filter_sql = " `tvshow`.`name` NOT REGEXP '" . Dba::escape($value) . "' AND ";
+ if (!empty($value)) {
+ $filter_sql = " `tvshow`.`name` NOT REGEXP '" . Dba::escape($value) . "' AND ";
+ }
break;
case 'exact_match':
$filter_sql = " `tvshow`.`name` = '" . Dba::escape($value) . "' AND ";
@@ -1695,10 +1741,14 @@ class Query
$filter_sql = " `label`.`name` LIKE '%" . Dba::escape($value) . "%' AND ";
break;
case 'regex_match':
- if (!empty($value)) $filter_sql = " `label`.`name` REGEXP '" . Dba::escape($value) . "' AND ";
+ if (!empty($value)) {
+ $filter_sql = " `label`.`name` REGEXP '" . Dba::escape($value) . "' AND ";
+ }
break;
case 'regex_not_match':
- if (!empty($value)) $filter_sql = " `label`.`name` NOT REGEXP '" . Dba::escape($value) . "' AND ";
+ if (!empty($value)) {
+ $filter_sql = " `label`.`name` NOT REGEXP '" . Dba::escape($value) . "' AND ";
+ }
break;
case 'starts_with':
$filter_sql = " `label`.`name` LIKE '" . Dba::escape($value) . "%' AND ";
@@ -1714,10 +1764,14 @@ class Query
$filter_sql = " `user_pvmsg`.`subject` LIKE '%" . Dba::escape($value) . "%' AND ";
break;
case 'regex_match':
- if (!empty($value)) $filter_sql = " `user_pvmsg`.`subject` REGEXP '" . Dba::escape($value) . "' AND ";
+ if (!empty($value)) {
+ $filter_sql = " `user_pvmsg`.`subject` REGEXP '" . Dba::escape($value) . "' AND ";
+ }
break;
case 'regex_not_match':
- if (!empty($value)) $filter_sql = " `user_pvmsg`.`subject` NOT REGEXP '" . Dba::escape($value) . "' AND ";
+ if (!empty($value)) {
+ $filter_sql = " `user_pvmsg`.`subject` NOT REGEXP '" . Dba::escape($value) . "' AND ";
+ }
break;
case 'starts_with':
$filter_sql = " `user_pvmsg`.`subject` LIKE '" . Dba::escape($value) . "%' AND ";
@@ -1746,10 +1800,55 @@ class Query
break;
} // end filter
break;
+ case 'podcast':
+ switch ($filter) {
+ case 'alpha_match':
+ $filter_sql = " `podcast`.`title` LIKE '%" . Dba::escape($value) . "%' AND ";
+ break;
+ case 'regex_match':
+ if (!empty($value)) {
+ $filter_sql = " `podcast`.`title` REGEXP '" . Dba::escape($value) . "' AND ";
+ }
+ break;
+ case 'regex_not_match':
+ if (!empty($value)) {
+ $filter_sql = " `podcast`.`title` NOT REGEXP '" . Dba::escape($value) . "' AND ";
+ }
+ break;
+ case 'starts_with':
+ $filter_sql = " `podcast`.`title` LIKE '" . Dba::escape($value) . "%' AND ";
+ break;
+ default:
+ // Rien a faire
+ break;
+ } // end filter
+ break;
+ case 'podcast_episode':
+ switch ($filter) {
+ case 'alpha_match':
+ $filter_sql = " `podcast_episode`.`title` LIKE '%" . Dba::escape($value) . "%' AND ";
+ break;
+ case 'regex_match':
+ if (!empty($value)) {
+ $filter_sql = " `podcast_episode`.`title` REGEXP '" . Dba::escape($value) . "' AND ";
+ }
+ break;
+ case 'regex_not_match':
+ if (!empty($value)) {
+ $filter_sql = " `podcast_episode`.`title` NOT REGEXP '" . Dba::escape($value) . "' AND ";
+ }
+ break;
+ case 'starts_with':
+ $filter_sql = " `podcast_episode`.`title` LIKE '" . Dba::escape($value) . "%' AND ";
+ break;
+ default:
+ // Rien a faire
+ break;
+ } // end filter
+ break;
} // end switch on type
return $filter_sql;
-
} // sql_filter
/**
@@ -1766,7 +1865,6 @@ class Query
private function logic_filter($object_id)
{
return true;
-
} // logic_filter
/**
@@ -1781,7 +1879,9 @@ class Query
*/
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
// different filters that apply to different fields
@@ -2118,15 +2218,42 @@ class Query
break;
}
break;
+ case 'podcast':
+ switch ($field) {
+ case 'title':
+ $sql = "`podcast`.`title`";
+ break;
+ }
+ break;
+ case 'podcast_episode':
+ switch ($field) {
+ case 'title':
+ $sql = "`podcast_episode`.`title`";
+ break;
+ case 'category':
+ $sql = "`podcast_episode`.`category`";
+ break;
+ case 'author':
+ $sql = "`podcast_episode`.`author`";
+ break;
+ case 'time':
+ $sql = "`podcast_episode`.`time`";
+ break;
+ case 'pubDate':
+ $sql = "`podcast_episode`.`pubDate`";
+ break;
+ }
+ break;
default:
// Rien a faire
break;
} // end switch
- if (isset($sql) && !empty($sql)) { return "$sql $order,"; }
+ if (isset($sql) && !empty($sql)) {
+ return "$sql $order,";
+ }
return "";
-
} // sql_sort
/**
@@ -2188,7 +2315,7 @@ class Query
if (!count($objects) or !is_array($objects)) {
return false;
}
- $type = $this->get_type();
+ $type = $this->get_type();
$where_sql = "WHERE `$type`.`id` IN (";
foreach ($objects as $object_id) {
@@ -2223,7 +2350,6 @@ class Query
$this->save_objects($results);
return true;
-
} // resort_objects
/**
@@ -2269,7 +2395,6 @@ class Query
}
return true;
-
} // save_objects
/**
@@ -2280,7 +2405,6 @@ class Query
public function get_state()
{
return $this->_state;
-
} // get_state
/**
@@ -2304,5 +2428,5 @@ class Query
{
$this->_state['ak'] = $ak;
}
-
} // query
+
diff --git a/sources/lib/class/random.class.php b/sources/lib/class/random.class.php
index 1179ba0..927382f 100644
--- a/sources/lib/class/random.class.php
+++ b/sources/lib/class/random.class.php
@@ -2,22 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; version 2
- * of the License.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -47,7 +46,6 @@ class Random
$results = Dba::fetch_assoc($db_results);
return $results['id'];
-
} // artist
/**
@@ -65,7 +63,6 @@ class Random
$results = Dba::fetch_assoc($db_results);
return $results['id'];
-
} // playlist
/**
@@ -80,10 +77,9 @@ class Random
$method_name = 'get_default';
}
$song_ids = self::$method_name(1);
- $song_id = array_pop($song_ids);
+ $song_id = array_pop($song_ids);
return $song_id;
-
} // get_single_song
/**
@@ -112,7 +108,6 @@ class Random
}
return $results;
-
} // get_default
/**
@@ -125,7 +120,7 @@ class Random
$results = array();
// Get the last album played by us
- $data = $GLOBALS['user']->get_recently_played('1', 'album');
+ $data = $GLOBALS['user']->get_recently_played('1', 'album');
$where_sql = "";
if ($data[0]) {
$where_sql = " AND `song`.`album`='" . $data[0] . "' ";
@@ -146,7 +141,6 @@ class Random
}
return $results;
-
} // get_album
/**
@@ -158,7 +152,7 @@ class Random
{
$results = array();
- $data = $GLOBALS['user']->get_recently_played('1','artist');
+ $data = $GLOBALS['user']->get_recently_played('1','artist');
$where_sql = "";
if ($data[0]) {
$where_sql = " AND `song`.`artist`='" . $data[0] . "' ";
@@ -179,7 +173,6 @@ class Random
}
return $results;
-
} // get_artist
/**
@@ -196,7 +189,11 @@ class Random
/* If they've passed -1 as limit then get everything */
$limit_sql = "";
- if ($data['random'] == "-1") { unset($data['random']); } else { $limit_sql = "LIMIT " . Dba::escape($limit); }
+ if ($data['random'] == "-1") {
+ unset($data['random']);
+ } else {
+ $limit_sql = "LIMIT " . Dba::escape($limit);
+ }
$search_data = Search::clean_request($data);
@@ -275,7 +272,7 @@ class Random
// Run the query generated above so we can while it
$db_results = Dba::read($sql);
- $results = array();
+ $results = array();
$size_total = 0;
$fuzzy_size = 0;
@@ -300,11 +297,12 @@ class Random
}
$size_total = $size_total + $new_size;
- $results[] = $row['id'];
+ $results[] = $row['id'];
// If we are within 4mb of target then jump ship
if (($data['size_limit'] - floor($size_total)) < 4) {
- break; }
+ break;
+ }
} // if size_limit
// If length really does matter
@@ -313,7 +311,8 @@ class Random
$new_time = floor($row['time'] / 60);
if ($fuzzy_time > 100) {
- break;;
+ break;
+ ;
}
// If the new one would go over skip!
@@ -323,7 +322,7 @@ class Random
}
$time_total = $time_total + $new_time;
- $results[] = $row['id'];
+ $results[] = $row['id'];
// If there are less then 2 min of free space return
if (($data['length'] - $time_total) < 2) {
@@ -334,7 +333,6 @@ class Random
if (!$data['size_limit'] && !$data['length']) {
$results[] = $row['id'];
}
-
} // end while results
switch ($type) {
@@ -351,12 +349,12 @@ class Random
$songs = array();
foreach ($results as $result) {
$artist = new Artist($result);
- $songs = array_merge($songs, $artist->get_songs());
+ $songs = array_merge($songs, $artist->get_songs());
}
return $songs;
default:
return false;
}
} // advanced
-
} //end of random class
+
diff --git a/sources/lib/class/rating.class.php b/sources/lib/class/rating.class.php
index 787c514..70286d4 100644
--- a/sources/lib/class/rating.class.php
+++ b/sources/lib/class/rating.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -39,11 +39,10 @@ class Rating extends database_object
*/
public function __construct($id, $type)
{
- $this->id = intval($id);
+ $this->id = intval($id);
$this->type = $type;
return true;
-
} // Constructor
/**
@@ -53,7 +52,7 @@ class Rating extends database_object
*/
public static function gc()
{
- $types = array('song', 'album', 'artist', 'video', 'tvshow', 'tvshow_season', 'playlist', 'label');
+ $types = array('song', 'album', 'artist', 'video', 'tvshow', 'tvshow_season', 'playlist', 'label', 'podcast', 'podcast_episode');
if ($object_type != null) {
if (in_array($object_type, $types)) {
@@ -76,13 +75,15 @@ class Rating extends database_object
*/
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();
$user_ratings = array();
$idlist = '(' . implode(',', $ids) . ')';
- $sql = "SELECT `rating`, `object_id` FROM `rating` " .
+ $sql = "SELECT `rating`, `object_id` FROM `rating` " .
"WHERE `user` = ? AND `object_id` IN $idlist " .
"AND `object_type` = ?";
$db_results = Dba::read($sql, array($GLOBALS['user']->id, $type));
@@ -119,7 +120,6 @@ class Rating extends database_object
}
return true;
-
} // build_cache
/**
@@ -129,29 +129,28 @@ class Rating extends database_object
*/
public function get_user_rating($user_id = null)
{
- if (is_null($user_id)) {
- $user_id = $GLOBALS['user']->id;
- }
+ if (is_null($user_id)) {
+ $user_id = $GLOBALS['user']->id;
+ }
- $key = 'rating_' . $this->type . '_user' . $user_id;
- if (parent::is_cached($key, $this->id)) {
- return parent::get_from_cache($key, $this->id);
- }
+ $key = 'rating_' . $this->type . '_user' . $user_id;
+ if (parent::is_cached($key, $this->id)) {
+ return parent::get_from_cache($key, $this->id);
+ }
- $sql = "SELECT `rating` FROM `rating` WHERE `user` = ? ".
+ $sql = "SELECT `rating` FROM `rating` WHERE `user` = ? " .
"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));
- $rating = 0;
+ $rating = 0;
- if ($results = Dba::fetch_assoc($db_results)) {
- $rating = $results['rating'];
- }
+ if ($results = Dba::fetch_assoc($db_results)) {
+ $rating = $results['rating'];
+ }
- parent::add_to_cache($key, $this->id, $rating);
- return $rating;
-
- } // get_user_rating
+ parent::add_to_cache($key, $this->id, $rating);
+ return $rating;
+ } // get_user_rating
/**
* get_average_rating
@@ -172,7 +171,6 @@ class Rating extends database_object
parent::add_to_cache('rating_' . $this->type . '_all', $this->id, $results['rating']);
return $results['rating'];
-
} // get_average_rating
/**
@@ -182,7 +180,7 @@ class Rating extends database_object
public static function get_highest_sql($type)
{
$type = Stats::validate_type($type);
- $sql = "SELECT `object_id` as `id`, AVG(`rating`) AS `rating` FROM rating" .
+ $sql = "SELECT `object_id` as `id`, AVG(`rating`) AS `rating` FROM rating" .
" WHERE object_type = '" . $type . "'";
if (AmpConfig::get('catalog_disable')) {
$sql .= " AND " . Catalog::get_enable_filter($type, '`object_id`');
@@ -219,7 +217,6 @@ class Rating extends database_object
}
return $results;
-
}
/**
@@ -261,7 +258,6 @@ class Rating extends database_object
}
return true;
-
} // set_rating
/**
@@ -272,16 +268,17 @@ class Rating extends database_object
public static function show($object_id, $type, $static=false)
{
// If ratings aren't enabled don't do anything
- if (!AmpConfig::get('ratings')) { return false; }
+ if (!AmpConfig::get('ratings')) {
+ return false;
+ }
$rating = new Rating($object_id, $type);
if ($static) {
- require AmpConfig::get('prefix') . '/templates/show_static_object_rating.inc.php';
+ require AmpConfig::get('prefix') . UI::find_template('show_static_object_rating.inc.php');
} else {
- require AmpConfig::get('prefix') . '/templates/show_object_rating.inc.php';
+ require AmpConfig::get('prefix') . UI::find_template('show_object_rating.inc.php');
}
-
} // show
-
} //end rating class
+
diff --git a/sources/lib/class/recommendation.class.php b/sources/lib/class/recommendation.class.php
index d5ad075..13a7f2b 100644
--- a/sources/lib/class/recommendation.class.php
+++ b/sources/lib/class/recommendation.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -37,9 +37,9 @@ class Recommendation
*/
public static function get_lastfm_results($method, $query)
{
- $api_key = AmpConfig::get('lastfm_api_key');
+ $api_key = AmpConfig::get('lastfm_api_key');
$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;
return self::query_lastfm($url);
}
@@ -56,7 +56,8 @@ class Recommendation
public static function album_search($artist, $album)
{
- $url = 'http://ws.audioscrobbler.com/1.0/album/' . urlencode($artist) . '/' . urlencode($album) . '/info.xml';
+ $api_key = AmpConfig::get('lastfm_api_key');
+ $url = 'http://ws.audioscrobbler.com/2.0/?method=album.getInfo&artist=' . urlencode($artist) . '&album=' . urlencode($album) . '&api_key=' . $api_key;
return self::query_lastfm($url);
}
@@ -75,14 +76,14 @@ class Recommendation
{
self::gc();
- $sql = "SELECT `id`, `last_update` FROM `recommendation` WHERE `object_type` = ? AND `object_id` = ?";
+ $sql = "SELECT `id`, `last_update` FROM `recommendation` WHERE `object_type` = ? AND `object_id` = ?";
$db_results = Dba::read($sql, array($type, $id));
if ($cache = Dba::fetch_assoc($db_results)) {
if ($get_items) {
$cache['items'] = array();
- $sql = "SELECT `recommendation_id`, `name`, `rel`, `mbid` FROM `recommendation_item` WHERE `recommendation` = ?";
- $db_results = Dba::read($sql, array($cache['id']));
+ $sql = "SELECT `recommendation_id`, `name`, `rel`, `mbid` FROM `recommendation_item` WHERE `recommendation` = ?";
+ $db_results = Dba::read($sql, array($cache['id']));
while ($results = Dba::fetch_assoc($db_results)) {
$cache['items'][] = array(
'id' => $results['recommendation_id'],
@@ -135,14 +136,14 @@ class Recommendation
$cache = self::get_recommendation_cache('song', $song_id, true);
if (!$cache['id']) {
$similars = array();
- $xml = self::get_lastfm_results('track.getsimilar', $query);
+ $xml = self::get_lastfm_results('track.getsimilar', $query);
if ($xml->similartracks) {
foreach ($xml->similartracks->children() as $child) {
- $name = $child->name;
+ $name = $child->name;
$local_id = null;
- $artist_name = $child->artist->name;
+ $artist_name = $child->artist->name;
$s_artist_name = Catalog::trim_prefix($artist_name);
$sql = "SELECT `song`.`id` FROM `song` " .
@@ -219,13 +220,13 @@ class Recommendation
$cache = self::get_recommendation_cache('artist', $artist_id, true);
if (!$cache['id']) {
$similars = array();
- $query = 'artist=' . rawurlencode($artist->name);
+ $query = 'artist=' . rawurlencode($artist->name);
$xml = self::get_lastfm_results('artist.getsimilar', $query);
foreach ($xml->similarartists->children() as $child) {
- $name = $child->name;
- $mbid = (string) $child->mbid;
+ $name = $child->name;
+ $mbid = (string) $child->mbid;
$local_id = null;
// First we check by MBID
@@ -245,7 +246,7 @@ class Recommendation
if (is_null($local_id)) {
$searchname = Catalog::trim_prefix($name);
$searchname = Dba::escape($searchname['string']);
- $sql = "SELECT `artist`.`id` FROM `artist` WHERE `name` = ?";
+ $sql = "SELECT `artist`.`id` FROM `artist` WHERE `name` = ?";
if (AmpConfig::get('catalog_disable')) {
$sql .= " AND " . Catalog::get_enable_filter('artist', '`artist`.`id`');
}
@@ -313,16 +314,16 @@ class Recommendation
$fullname = $artist->f_full_name;
// Data newer than 6 months, use it
- if (($artist->last_update + 15768000) > time()) {
- $results = array();
- $results['id'] = $artist_id;
- $results['summary'] = $artist->summary;
+ if (($artist->last_update + 15768000) > time() || $artist->manual_update) {
+ $results = array();
+ $results['id'] = $artist_id;
+ $results['summary'] = $artist->summary;
$results['placeformed'] = $artist->placeformed;
- $results['yearformed'] = $artist->yearformed;
- $results['largephoto'] = Art::url($artist->id, 'artist');
- $results['smallphoto'] = $results['largephoto']; // TODO: Change to thumb size?
+ $results['yearformed'] = $artist->yearformed;
+ $results['largephoto'] = Art::url($artist->id, 'artist');
+ $results['smallphoto'] = $results['largephoto']; // TODO: Change to thumb size?
$results['mediumphoto'] = $results['largephoto']; // TODO: Change to thumb size?
- $results['megaphoto'] = $results['largephoto'];
+ $results['megaphoto'] = $results['largephoto'];
return $results;
}
}
@@ -331,14 +332,15 @@ class Recommendation
$xml = self::get_lastfm_results('artist.getinfo', $query);
- $results = array();
- $results['summary'] = strip_tags(preg_replace("#.#", "", (string) $xml->artist->bio->summary));
+ $results = array();
+ $results['summary'] = strip_tags(preg_replace("#.#", "", (string) $xml->artist->bio->summary));
+ $results['summary'] = str_replace("Read more on Last.fm", "", $results['summary']);
$results['placeformed'] = (string) $xml->artist->bio->placeformed;
- $results['yearformed'] = (string) $xml->artist->bio->yearformed;
- $results['smallphoto'] = $xml->artist->image[0];
+ $results['yearformed'] = (string) $xml->artist->bio->yearformed;
+ $results['smallphoto'] = $xml->artist->image[0];
$results['mediumphoto'] = $xml->artist->image[1];
- $results['largephoto'] = $xml->artist->image[2];
- $results['megaphoto'] = $xml->artist->image[4];
+ $results['largephoto'] = $xml->artist->image[2];
+ $results['megaphoto'] = $xml->artist->image[4];
if ($artist) {
$results['id'] = $artist->id;
@@ -346,17 +348,17 @@ class Recommendation
$artist->update_artist_info($results['summary'], $results['placeformed'], $results['yearformed']);
$image = Art::get_from_source(array('url' => $results['megaphoto']), 'artist');
- $rurl = pathinfo($results['megaphoto']);
- $mime = 'image/' . $rurl['extension'];
- $art = new Art($artist->id, 'artist');
+ $rurl = pathinfo($results['megaphoto']);
+ $mime = 'image/' . $rurl['extension'];
+ $art = new Art($artist->id, 'artist');
$art->reset();
$art->insert($image, $mime);
$results['largephoto'] = Art::url($artist->id, 'artist');
- $results['megaphoto'] = $results['largephoto'];
+ $results['megaphoto'] = $results['largephoto'];
}
}
return $results;
} // get_artist_info
-
} // end of recommendation class
+
diff --git a/sources/lib/class/registration.class.php b/sources/lib/class/registration.class.php
index 2a6d4cd..8d80e17 100644
--- a/sources/lib/class/registration.class.php
+++ b/sources/lib/class/registration.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -35,7 +35,6 @@ class Registration
public function __construct()
{
// Rien a faire
-
} // constructor
/**
@@ -66,7 +65,7 @@ Your account is currently inactive. You cannot use it until you've visited the f
Thank you for registering
"), $username, AmpConfig::get('web_path') . "/register.php?action=validate&username=$username&auth=$validation");
- $mailer->recipient = $email;
+ $mailer->recipient = $email;
$mailer->recipient_name = $fullname;
if (!AmpConfig::get('admin_enable_required')) {
@@ -89,7 +88,6 @@ Website: %s
}
return true;
-
} // send_confirmation
/**
@@ -107,7 +105,7 @@ Website: %s
$mailer->message = sprintf(T_("Your account %s has been enabled\n\n
Please logon using %s"), $username, AmpConfig::get('web_path') . "/login.php");
- $mailer->recipient = $email;
+ $mailer->recipient = $email;
$mailer->recipient_name = $fullname;
$mailer->send();
@@ -121,18 +119,21 @@ Website: %s
{
$filename = AmpConfig::get('prefix') . '/config/registration_agreement.php';
- if (!file_exists($filename)) { return false; }
+ if (!file_exists($filename)) {
+ return false;
+ }
/* Check for existance */
$fp = fopen($filename,'r');
- if (!$fp) { return false; }
+ if (!$fp) {
+ return false;
+ }
$data = fread($fp,filesize($filename));
/* Scrub and show */
echo $data;
-
} // show_agreement
-
} // end registration class
+
diff --git a/sources/lib/class/scrobbler.class.php b/sources/lib/class/scrobbler.class.php
index 26601bf..e89062c 100644
--- a/sources/lib/class/scrobbler.class.php
+++ b/sources/lib/class/scrobbler.class.php
@@ -2,62 +2,116 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
class scrobbler
{
public $error_msg;
- public $username;
- public $password;
public $challenge;
- public $submit_host;
- public $submit_port;
- public $submit_url;
+ public $host;
+ public $scheme;
+ public $api_key;
public $queued_tracks;
- public $reset_handshake = false;
- public $scrobble_host = 'post.audioscrobbler.com';
+ private $secret;
/**
* Constructor
* This is the constructer it takes a username and password
*/
- public function __construct($username, $password,$host='',$port='',$url='',$challenge='',$scrobble_host='')
+ public function __construct($api_key, $scheme='https',$host='',$challenge='', $secret='')
{
- $this->error_msg = '';
- $this->username = trim($username);
- $this->password = trim($password);
- $this->challenge = $challenge;
- $this->submit_host = $host;
- $this->submit_port = $port;
- $this->submit_url = $url;
+ $this->error_msg = '';
+ $this->challenge = $challenge;
+ $this->host = $host;
+ $this->scheme = $scheme;
+ $this->api_key = $api_key;
+ $this->secret =$secret;
$this->queued_tracks = array();
- if ($scrobble_host) { $this->scrobble_host = $scrobble_host; }
-
} // scrobbler
+ /**
+ * get_api_sig
+ * Provide the API signature for calling Last.fm / Libre.fm services
+ * It is the md5 of the of all parameter plus API's secret
+ */
+ public function get_api_sig($vars=null)
+ {
+ ksort($vars);
+ $sig = '';
+ foreach ($vars as $name => $value) {
+ $sig .= $name . $value;
+ }
+ $sig .= $this->secret;
+ $sig = md5($sig);
+ return $sig;
+ } // get_api_sig
+
+ /**
+ * call_url
+ * This is a generic caller for HTTP requests
+ * It need the method (GET/POST), the url and the parameters
+ */
+ public function call_url($url, $method='GET', $vars=null)
+ {
+ // Encode parameters per RFC1738
+ $params=http_build_query($vars);
+ $opts = array(
+ 'http'=>array(
+ 'method'=>$method,
+ 'header'=> array(
+ 'Host: ' . $this->host,
+ 'User-Agent: Ampache/' . AmpConfig::get('version')
+ ),
+ )
+ );
+ // POST request need parameters in body and additional headers
+ if ($method == 'POST') {
+ $opts['http']['content'] = $params;
+ $opts['http']['header'][] = 'Content-type: application/x-www-form-urlencoded';
+ $opts['http']['header'][] = 'Content-length: ' . strlen($params);
+ $params ='';
+ }
+ $context = stream_context_create($opts);
+ if ($params!='') {
+ // If there are paramters for GET request, adding the "?" caracter before
+ $params='?' . $params;
+ }
+ $target = $this->scheme . '://' . $this->host . $url . $params;
+ $fp = @fopen($target, 'r', false, $context);
+ if (!$fp) {
+ debug_event('Scrobbler', 'Cannot access ' . $target, 1);
+ return false;
+ }
+ ob_start();
+ fpassthru($fp);
+ $buffer = ob_get_contents();
+ ob_end_clean();
+ fclose($fp);
+ return $buffer;
+ } // call_url
+
/**
* get_error_msg
*/
public function get_error_msg()
{
return $this->error_msg;
-
} // get_error_msg
/**
@@ -66,88 +120,53 @@ class scrobbler
public function get_queue_count()
{
return count($this->queued_tracks);
-
} // get_queue_count
/**
- * handshake
- * 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
+ * get_session_key
+ * This is a generic caller for HTTP requests
+ * It need the method (GET/POST), the url and the parameters
*/
- public function handshake()
+ public function get_session_key ($token=null)
{
- $data = array();
- $as_socket = fsockopen($this->scrobble_host, 80, $errno, $errstr, 2);
- if (!$as_socket) {
- $this->error_msg = $errstr;
- return false;
+ if (!is_null($token)) {
+ $vars = array(
+ 'method' => 'auth.getSession',
+ 'api_key'=> $this->api_key,
+ 'token' => $token
+ );
+ //sign the call
+ $sig = $this->get_api_sig($vars);
+ $vars['api_sig'] = $sig;
+ //call the getSession API
+ $response=$this->call_url('/2.0/', 'GET', $vars);
+ $xml = simplexml_load_string($response);
+ if ($xml) {
+ $status = (string) $xml['status'];
+ if ($status == 'ok') {
+ if ($xml->session && $xml->session->key) {
+ return $xml->session->key;
+ } else {
+ $this->error_msg = 'Did not receive a valid response';
+ return false;
+ }
+ } else {
+ $this->error_msg = $xml->error;
+ return false;
+ }
+ } else {
+ $this->error_msg = 'Did not receive a valid response';
+ return false;
+ }
}
-
- $username = rawurlencode($this->username);
- $timestamp = time();
- $auth_token = rawurlencode(md5($this->password . $timestamp));
-
- $get_string = "GET /?hs=true&p=1.2&c=apa&v=0.1&u=$username&t=$timestamp&a=$auth_token HTTP/1.1\r\n";
-
- fwrite($as_socket, $get_string);
- fwrite($as_socket, "Host: $this->scrobble_host\r\n");
- fwrite($as_socket, "Accept: */*\r\n\r\n");
-
- $buffer = '';
- while (!feof($as_socket)) {
- $buffer .= fread($as_socket, 4096);
- }
- fclose($as_socket);
- $split_response = preg_split("/\r\n\r\n/", $buffer);
- if (!isset($split_response[1])) {
- $this->error_msg = 'Did not receive a valid response';
- return false;
- }
- $response = explode("\n", $split_response[1]);
-
- // Handle the fact Libre.FM has extranious values at the start of it's handshake response
- if (is_numeric(trim($response['0']))) {
- array_shift($response);
- debug_event('SCROBBLER','Junk in handshake, removing first line',1);
- }
- if (substr($response[0], 0, 6) == 'FAILED') {
- $this->error_msg = substr($response[0], 7);
- return false;
- }
- if (substr($response[0], 0, 7) == 'BADUSER') {
- $this->error_msg = 'Invalid Username';
- return false;
- }
- 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';
- return false;
- }
- if (substr($response[0], 0, 6) == 'UPDATE') {
- $this->error_msg = 'You need to update your client: '.substr($response[0], 7);
- return false;
- }
-
- if (preg_match('/http:\/\/([^\/]+)\/(.*)$/', $response[3], $matches)) {
- $host_parts = explode(":",$matches[1]);
- $data['submit_host'] = $host_parts[0];
- $data['submit_port'] = $host_parts[1] ? $host_parts[1] : '80';
- $data['submit_url'] = '/' . $matches[2];
- } else {
- $this->error_msg = "Invalid POST URL returned, unable to continue. Sent:\n$get_string\n----\nReceived:\n" . $buffer .
- "\n---------\nExpected:" . print_r($response, true);
- return false;
- }
-
- // Remove any extra junk around the challenge
- $data['challenge'] = trim($response[1]);
- return $data;
-
- } // handshake
+ $this->error_msg = 'Need a token to call getSession';
+ return false;
+ } // get_session_key
/**
* queue_track
- * This queues the LastFM track by storing it in this object, it doesn't actually
- * submit the track or talk to LastFM in anyway, kind of useless for our uses but its
+ * This queues the LastFM / Libre.fm track by storing it in this object, it doesn't actually
+ * submit the track or talk to LastFM / Libre in anyway, kind of useless for our uses but its
* here, and that's how it is.
*/
public function queue_track($artist, $album, $title, $timestamp, $length,$track)
@@ -157,23 +176,22 @@ class scrobbler
return false;
}
- $newtrack = array();
+ $newtrack = array();
$newtrack['artist'] = $artist;
- $newtrack['album'] = $album;
- $newtrack['title'] = $title;
- $newtrack['track'] = $track;
+ $newtrack['album'] = $album;
+ $newtrack['title'] = $title;
+ $newtrack['track'] = $track;
$newtrack['length'] = $length;
- $newtrack['time'] = $timestamp;
+ $newtrack['time'] = $timestamp;
$this->queued_tracks[$timestamp] = $newtrack;
return true;
-
} // queue_track
/**
* submit_tracks
- * 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
+ * This actually talks to LastFM / Libre.fm submiting the tracks that are queued up.
+ * It passed the API key, session key combinted with the signature
*/
public function submit_tracks()
{
@@ -186,85 +204,78 @@ class scrobbler
//sort array by timestamp
ksort($this->queued_tracks);
- // build the query string
- $query_str = 's='.rawurlencode($this->challenge).'&';
-
- $i = 0;
-
+ // Build the query string (encoded per RFC1738 by the call method)
+ $i = 0;
+ $vars= array();
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 .= "m[$i]=&l[$i]=".rawurlencode($track['length'])."&i[$i]=".rawurlencode($track['time'])."&";
- $query_str .= "n[$i]=" . rawurlencode($track['track']) . "&o[$i]=P&r[$i]=&";
+ //construct array of parameters for each song
+ $vars["artist[$i]"] = $track['artist'];
+ $vars["track[$i]"] = $track['title'];
+ $vars["timestamp[$i]"] = $track['time'];
+ $vars["album[$i]"] = $track['album'];
+ $vars["trackNumber[$i]"] = $track['track'];
+ $vars["duration[$i]"] = $track['length'];
$i++;
}
+ // Add the method, API and session keys
+ $vars['method'] = 'track.scrobble';
+ $vars['api_key'] = $this->api_key;
+ $vars['sk'] = $this->challenge;
- if (!trim($this->submit_host) || !$this->submit_port) {
- $this->reset_handshake = true;
- return false;
- }
+ // Sign the call
+ $sig = $this->get_api_sig($vars);
+ $vars['api_sig'] = $sig;
- $as_socket = fsockopen($this->submit_host, intval($this->submit_port), $errno, $errstr, 2);
-
- if (!$as_socket) {
- $this->error_msg = $errstr;
- $this->reset_handshake = true;
- return false;
- }
-
- $action = "POST ".$this->submit_url." HTTP/1.0\r\n";
- fwrite($as_socket, $action);
- fwrite($as_socket, "Host: ".$this->submit_host."\r\n");
- fwrite($as_socket, "Accept: */*\r\n");
- fwrite($as_socket, "User-Agent: Ampache/3.6\r\n");
- fwrite($as_socket, "Content-type: application/x-www-form-urlencoded\r\n");
- fwrite($as_socket, "Content-length: ".strlen($query_str)."\r\n\r\n");
-
- fwrite($as_socket, $query_str."\r\n\r\n");
- // Allow us to debug this
- debug_event('SCROBBLER','Query String:' . $query_str,6);
-
- $buffer = '';
- while (!feof($as_socket)) {
- $buffer .= fread($as_socket, 8192);
- }
- fclose($as_socket);
-
- $split_response = preg_split("/\r\n\r\n/", $buffer);
- if (!isset($split_response[1])) {
+ // Call the method and parse response
+ $response=$this->call_url('/2.0/', 'POST', $vars);
+ $xml = simplexml_load_string($response);
+ if ($xml) {
+ $status = (string) $xml['status'];
+ if ($status == 'ok') {
+ return true;
+ } else {
+ $this->error_msg = $xml->error;
+ return false;
+ }
+ } else {
$this->error_msg = 'Did not receive a valid response';
- $this->reset_handshake = true;
return false;
}
- $response = explode("\n", $split_response[1]);
- if (!isset($response[0])) {
- $this->error_msg = 'Unknown error submitting tracks'.
- "\nDebug output:\n".$buffer;
- $this->reset_handshake = true;
- return false;
- }
- if (substr($response[0], 0, 6) == 'FAILED') {
- $this->error_msg = $response[0];
- $this->reset_handshake = true;
- return false;
- }
- if (substr($response[0], 0, 7) == 'BADAUTH') {
- $this->error_msg = 'Invalid username/password (' . trim($response[0]) . ')';
- return false;
- }
- if (substr($response[0],0,10) == 'BADSESSION') {
- $this->error_msg = 'Invalid Session passed (' . trim($response[0]) . ')';
- $this->reset_handshake = true;
- return false;
- }
- if (substr($response[0], 0, 2) != 'OK') {
- $this->error_msg = 'Response Not ok, unknown error'.
- "\nDebug output:\n".$buffer;
- $this->reset_handshake = true;
- return false;
- }
-
- return true;
-
} // submit_tracks
+ /**
+ * love
+ * This takes care of spreading your love to the world
+ * It passed the API key, session key combinted with the signature
+ */
+ public function love($is_loved, $type, $artist = '', $title = '', $album = '')
+ {
+ $vars['track'] = $title;
+ $vars['artist'] = $artist;
+ // Add the method, API and session keys
+ $vars['method'] = $is_loved ? 'track.love' : 'track.unlove';
+ $vars['api_key'] = $this->api_key;
+ $vars['sk'] = $this->challenge;
+
+ // Sign the call
+ $sig = $this->get_api_sig($vars);
+ $vars['api_sig'] = $sig;
+
+ // Call the method and parse response
+ $response=$this->call_url('/2.0/', 'POST', $vars);
+ $xml = simplexml_load_string($response);
+ if ($xml) {
+ $status = (string) $xml['status'];
+ if ($status == 'ok') {
+ return true;
+ } else {
+ $this->error_msg = $xml->error;
+ return false;
+ }
+ } else {
+ $this->error_msg = 'Did not receive a valid response';
+ return false;
+ }
+ } // love
} // end audioscrobbler class
+
diff --git a/sources/lib/class/scrobbler_async.class.php b/sources/lib/class/scrobbler_async.class.php
index 2718adb..88c4015 100644
--- a/sources/lib/class/scrobbler_async.class.php
+++ b/sources/lib/class/scrobbler_async.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -24,7 +24,7 @@ class scrobbler_async extends Thread
{
public function __construct($user, $song_info)
{
- $this->user = $user;
+ $this->user = $user;
$this->song_info = $song_info;
}
diff --git a/sources/lib/class/search.class.php b/sources/lib/class/search.class.php
index 0942075..79016f2 100644
--- a/sources/lib/class/search.class.php
+++ b/sources/lib/class/search.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -30,9 +30,9 @@ class Search extends playlist_object
public $searchtype;
public $rules;
public $logic_operator = 'AND';
- public $type = 'public';
- public $random = false;
- public $limit = 0;
+ public $type = 'public';
+ public $random = false;
+ public $limit = 0;
public $basetypes;
public $types;
@@ -52,7 +52,7 @@ class Search extends playlist_object
$this->$key = $value;
}
- $this->rules = unserialize($this->rules);
+ $this->rules = json_decode($this->rules, true);
}
// Define our basetypes
@@ -162,7 +162,7 @@ class Search extends playlist_object
'sql' => '<=>'
);
- $this->basetypes['boolean_numeric'][] = array(
+ $this->basetypes['boolean_numeric'][] = array(
'name' => 'ne',
'description' => T_('is not'),
'sql' => '<>'
@@ -193,6 +193,7 @@ class Search extends playlist_object
'description' => T_('after'),
'sql' => '>'
);
+ $this->basetypes['multiple'] = array_merge($this->basetypes['text'], $this->basetypes['numeric']);
switch ($searchtype) {
case 'song':
@@ -253,6 +254,13 @@ class Search extends playlist_object
'widget' => array('input', 'text')
);
+ $this->types[] = array(
+ 'name' => 'album_tag',
+ 'label' => T_('Album tag'),
+ 'type' => 'text',
+ 'widget' => array('input', 'text')
+ );
+
$this->types[] = array(
'name' => 'file',
'label' => T_('Filename'),
@@ -369,7 +377,7 @@ class Search extends playlist_object
$this->types[] = array(
'name' => 'playlist',
'label' => T_('Playlist'),
- 'type' => 'boolean_numeric',
+ 'type' => 'boolean_numeric',
'widget' => array('select', $playlists)
);
@@ -382,7 +390,7 @@ class Search extends playlist_object
$playlists = array();
foreach (Search::get_searches() as $playlistid) {
- // Slightly different from the above so we don't instigate
+ // Slightly different from the above so we don't instigate
// a vicious loop.
$playlists[$playlistid] = Search::get_name_byid($playlistid);
}
@@ -393,9 +401,22 @@ class Search extends playlist_object
'widget' => array('select', $playlists)
);
+ $metadataFields = array();
+ $metadataFieldRepository = new \Lib\Metadata\Repository\MetadataField();
+ foreach ($metadataFieldRepository->findAll() as $metadata) {
+ $metadataFields[$metadata->getId()] = $metadata->getName();
+ }
+ $this->types[] = array(
+ 'name' => 'metadata',
+ 'label' => T_('Metadata'),
+ 'type' => 'multiple',
+ 'subtypes' => $metadataFields,
+ 'widget' => array('subtypes', array('input', 'text'))
+ );
+
$licenses = array();
foreach (License::get_licenses() as $license_id) {
- $license = new License($license_id);
+ $license = new License($license_id);
$licenses[$license_id] = $license->name;
}
if (AmpConfig::get('licensing')) {
@@ -406,6 +427,7 @@ class Search extends playlist_object
'widget' => array('select', $licenses)
);
}
+
break;
case 'album':
$this->types[] = array(
@@ -547,7 +569,6 @@ class Search extends playlist_object
);
break;
} // end switch on searchtype
-
} // end constructor
/**
@@ -560,7 +581,7 @@ class Search extends playlist_object
$request = array();
foreach ($data as $key => $value) {
$prefix = substr($key, 0, 4);
- $value = trim($value);
+ $value = trim($value);
if ($prefix == 'rule' && strlen($value)) {
$request[$key] = Dba::escape($value);
@@ -603,11 +624,11 @@ class Search extends playlist_object
*/
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);
- $r = Dba::fetch_assoc($db_results);
+ $r = Dba::fetch_assoc($db_results);
return $r['name'];
- }
+ }
/**
* get_searches
@@ -637,9 +658,9 @@ class Search extends playlist_object
*/
public static function run($data)
{
- $limit = intval($data['limit']);
+ $limit = intval($data['limit']);
$offset = intval($data['offset']);
- $data = Search::clean_request($data);
+ $data = Search::clean_request($data);
$search = new Search(null, $data['type']);
$search->parse_rules($data);
@@ -649,12 +670,14 @@ class Search extends playlist_object
$limit_sql = "";
if ($limit > 0) {
$limit_sql = ' LIMIT ';
- if ($offset) $limit_sql .= $offset . ",";
+ if ($offset) {
+ $limit_sql .= $offset . ",";
+ }
$limit_sql .= $limit;
}
$search_info = $search->to_sql();
- $sql = $search_info['base'] . ' ' . $search_info['table_sql'];
+ $sql = $search_info['base'] . ' ' . $search_info['table_sql'];
if (!empty($search_info['where_sql'])) {
$sql .= ' WHERE ' . $search_info['where_sql'];
}
@@ -685,7 +708,7 @@ class Search extends playlist_object
*/
public function delete()
{
- $id = Dba::escape($this->id);
+ $id = Dba::escape($this->id);
$sql = "DELETE FROM `search` WHERE `id` = ?";
Dba::write($sql, array($id));
@@ -700,7 +723,7 @@ class Search extends playlist_object
{
parent::format();
- $this->link = AmpConfig::get('web_path') . '/smartplaylist.php?action=show_playlist&playlist_id=' . $this->id;
+ $this->link = AmpConfig::get('web_path') . '/smartplaylist.php?action=show_playlist&playlist_id=' . $this->id;
$this->f_link = '' . $this->f_name . '';
}
@@ -715,7 +738,7 @@ class Search extends playlist_object
$results = array();
$sqltbl = $this->to_sql();
- $sql = $sqltbl['base'] . ' ' . $sqltbl['table_sql'];
+ $sql = $sqltbl['base'] . ' ' . $sqltbl['table_sql'];
if (!empty($sqltbl['where_sql'])) {
$sql .= ' WHERE ' . $sqltbl['where_sql'];
}
@@ -755,7 +778,7 @@ class Search extends playlist_object
$results = array();
$sqltbl = $this->to_sql();
- $sql = $sqltbl['base'] . ' ' . $sqltbl['table_sql'];
+ $sql = $sqltbl['base'] . ' ' . $sqltbl['table_sql'];
if (!empty($sqltbl['where_sql'])) {
$sql .= ' WHERE ' . $sqltbl['where_sql'];
}
@@ -813,7 +836,8 @@ class Search extends playlist_object
$this->rules[] = array(
$value,
$this->basetypes[$this->name_to_basetype($value)][$data['rule_' . $ruleID . '_operator']]['name'],
- $input
+ $input,
+ $data['rule_' . $ruleID . '_subtype']
);
}
}
@@ -832,16 +856,16 @@ class Search extends playlist_object
if (! $this->name) {
$this->name = $GLOBALS['user']->username . ' - ' . date('Y-m-d H:i:s', time());
}
- $sql = "SELECT `id` FROM `search` WHERE `name` = ?";
+ $sql = "SELECT `id` FROM `search` WHERE `name` = ?";
$db_results = Dba::read($sql, array($this->name));
if (Dba::num_rows($db_results)) {
$this->name .= uniqid('', true);
}
$sql = "INSERT INTO `search` (`name`, `type`, `user`, `rules`, `logic_operator`, `random`, `limit`) VALUES (?, ?, ?, ?, ?, ?, ?)";
- Dba::write($sql, array($this->name, $this->type, $GLOBALS['user']->id, serialize($this->rules), $this->logic_operator, $this->random, $this->limit));
+ Dba::write($sql, array($this->name, $this->type, $GLOBALS['user']->id, json_encode($this->rules), $this->logic_operator, $this->random ? 1 : 0, $this->limit));
$insert_id = Dba::insert_id();
- $this->id = $insert_id;
+ $this->id = $insert_id;
return $insert_id;
}
@@ -857,7 +881,7 @@ class Search extends playlist_object
foreach ($this->rules as $rule) {
$js .= '';
+ $rule[1] . '","' . $rule[2] . '", "' . $rule[3] . '"); ';
}
return $js;
}
@@ -880,10 +904,10 @@ class Search extends playlist_object
public function update(array $data = null)
{
if ($data && is_array($data)) {
- $this->name = $data['name'];
- $this->type = $data['pl_type'];
+ $this->name = $data['name'];
+ $this->type = $data['pl_type'];
$this->random = $data['random'];
- $this->limit = $data['limit'];
+ $this->limit = $data['limit'];
}
if (!$this->id) {
@@ -891,7 +915,7 @@ class Search extends playlist_object
}
$sql = "UPDATE `search` SET `name` = ?, `type` = ?, `rules` = ?, `logic_operator` = ?, `random` = ?, `limit` = ? WHERE `id` = ?";
- Dba::write($sql, array($this->name, $this->type, serialize($this->rules), $this->logic_operator, $this->random, $this->limit, $this->id));
+ Dba::write($sql, array($this->name, $this->type, json_encode($this->rules), $this->logic_operator, $this->random, $this->limit, $this->id));
return $this->id;
}
@@ -937,15 +961,15 @@ class Search extends playlist_object
{
$sql_logic_operator = $this->logic_operator;
- $where = array();
- $table = array();
- $join = array();
- $group = array();
- $having = array();
+ $where = array();
+ $table = array();
+ $join = array();
+ $group = array();
+ $having = array();
$join['tag'] = array();
foreach ($this->rules as $rule) {
- $type = $this->name_to_basetype($rule[0]);
+ $type = $this->name_to_basetype($rule[0]);
$operator = array();
foreach ($this->basetypes[$type] as $op) {
if ($op['name'] == $rule[1]) {
@@ -953,7 +977,7 @@ class Search extends playlist_object
break;
}
}
- $input = $this->_mangle_data($rule[2], $type, $operator);
+ $input = $this->_mangle_data($rule[2], $type, $operator);
$sql_match_operator = $operator['sql'];
switch ($rule[0]) {
@@ -967,30 +991,30 @@ class Search extends playlist_object
if ($this->type != "public") {
$where[] = "COALESCE(`rating`.`rating`,0) $sql_match_operator '$input'";
} else {
- $group[] = "`album`.`id`";
- $having[] = "ROUND(AVG(`rating`.`rating`)) $sql_match_operator '$input'";
+ $group[] = "`album`.`id`";
+ $having[] = "ROUND(AVG(IFNULL(`rating`.`rating`,0))) $sql_match_operator '$input'";
}
$join['rating'] = true;
break;
case 'catalog':
- $where[] = "`song`.`catalog` $sql_match_operator '$input'";
+ $where[] = "`song`.`catalog` $sql_match_operator '$input'";
$join['song'] = true;
break;
case 'tag':
- $key = md5($input . $sql_match_operator);
- $where[] = "`realtag_$key`.`match` > 0";
+ $key = md5($input . $sql_match_operator);
+ $where[] = "`realtag_$key`.`match` > 0";
$join['tag'][$key] = "$sql_match_operator '$input'";
break;
case 'image height':
- $where[] = "`image`.`height` $sql_match_operator '$input'";
+ $where[] = "`image`.`height` $sql_match_operator '$input'";
$join['image'] = true;
break;
case 'image width':
- $where[] = "`image`.`width` $sql_match_operator '$input'";
+ $where[] = "`image`.`width` $sql_match_operator '$input'";
$join['image'] = true;
break;
case 'artist':
- $where[] = "`artist`.`name` $sql_match_operator '$input'";
+ $where[] = "`artist`.`name` $sql_match_operator '$input'";
$join['artist'] = true;
break;
default:
@@ -999,7 +1023,7 @@ class Search extends playlist_object
} // switch on ruletype
} // foreach rule
- $join['song'] = $join['song'] || AmpConfig::get('catalog_disable');
+ $join['song'] = $join['song'] || AmpConfig::get('catalog_disable');
$join['catalog'] = AmpConfig::get('catalog_disable');
$where_sql = implode(" $sql_logic_operator ", $where);
@@ -1007,7 +1031,7 @@ class Search extends playlist_object
foreach ($join['tag'] as $key => $value) {
$table['tag_' . $key] =
"LEFT JOIN (" .
- "SELECT `object_id`, COUNT(`name`) AS `match` ".
+ "SELECT `object_id`, COUNT(`name`) AS `match` " .
"FROM `tag` LEFT JOIN `tag_map` " .
"ON `tag`.`id`=`tag_map`.`tag_id` " .
"WHERE `tag_map`.`object_type`='album' " .
@@ -1027,7 +1051,7 @@ class Search extends playlist_object
}
}
if ($join['rating']) {
- $userid = intval($GLOBALS['user']->id);
+ $userid = intval($GLOBALS['user']->id);
$table['rating'] = "LEFT JOIN `rating` ON `rating`.`object_type`='album' ";
if ($this->type != 'public') {
$table['rating'] .= "AND `rating`.`user`='$userid' ";
@@ -1040,8 +1064,8 @@ class Search extends playlist_object
$where_sql .= " AND `image`.`size`='original'";
}
- $table_sql = implode(' ', $table);
- $group_sql = implode(', ', $group);
+ $table_sql = implode(' ', $table);
+ $group_sql = implode(', ', $group);
$having_sql = implode(" $sql_logic_operator ", $having);
return array(
@@ -1064,15 +1088,15 @@ class Search extends playlist_object
private function artist_to_sql()
{
$sql_logic_operator = $this->logic_operator;
- $where = array();
- $table = array();
- $join = array();
- $group = array();
- $having = array();
- $join['tag'] = array();
+ $where = array();
+ $table = array();
+ $join = array();
+ $group = array();
+ $having = array();
+ $join['tag'] = array();
foreach ($this->rules as $rule) {
- $type = $this->name_to_basetype($rule[0]);
+ $type = $this->name_to_basetype($rule[0]);
$operator = array();
foreach ($this->basetypes[$type] as $op) {
if ($op['name'] == $rule[1]) {
@@ -1080,7 +1104,7 @@ class Search extends playlist_object
break;
}
}
- $input = $this->_mangle_data($rule[2], $type, $operator);
+ $input = $this->_mangle_data($rule[2], $type, $operator);
$sql_match_operator = $operator['sql'];
switch ($rule[0]) {
@@ -1094,8 +1118,8 @@ class Search extends playlist_object
$where[] = "`artist`.`placeformed` $sql_match_operator '$input'";
break;
case 'tag':
- $key = md5($input . $sql_match_operator);
- $where[] = "`realtag_$key`.`match` > 0";
+ $key = md5($input . $sql_match_operator);
+ $where[] = "`realtag_$key`.`match` > 0";
$join['tag'][$key] = "$sql_match_operator '$input'";
break;
default:
@@ -1104,7 +1128,7 @@ class Search extends playlist_object
} // switch on ruletype
} // foreach rule
- $join['song'] = $join['song'] || AmpConfig::get('catalog_disable');
+ $join['song'] = $join['song'] || AmpConfig::get('catalog_disable');
$join['catalog'] = AmpConfig::get('catalog_disable');
$where_sql = implode(" $sql_logic_operator ", $where);
@@ -1112,7 +1136,7 @@ class Search extends playlist_object
foreach ($join['tag'] as $key => $value) {
$table['tag_' . $key] =
"LEFT JOIN (" .
- "SELECT `object_id`, COUNT(`name`) AS `match` ".
+ "SELECT `object_id`, COUNT(`name`) AS `match` " .
"FROM `tag` LEFT JOIN `tag_map` " .
"ON `tag`.`id`=`tag_map`.`tag_id` " .
"WHERE `tag_map`.`object_type`='artist' " .
@@ -1130,8 +1154,8 @@ class Search extends playlist_object
}
}
- $table_sql = implode(' ', $table);
- $group_sql = implode(', ', $group);
+ $table_sql = implode(' ', $table);
+ $group_sql = implode(', ', $group);
$having_sql = implode(" $sql_logic_operator ", $having);
return array(
@@ -1154,15 +1178,15 @@ class Search extends playlist_object
{
$sql_logic_operator = $this->logic_operator;
- $where = array();
- $table = array();
- $join = array();
- $group = array();
- $having = array();
+ $where = array();
+ $table = array();
+ $join = array();
+ $group = array();
+ $having = array();
$join['tag'] = array();
foreach ($this->rules as $rule) {
- $type = $this->name_to_basetype($rule[0]);
+ $type = $this->name_to_basetype($rule[0]);
$operator = array();
foreach ($this->basetypes[$type] as $op) {
if ($op['name'] == $rule[1]) {
@@ -1170,37 +1194,43 @@ class Search extends playlist_object
break;
}
}
- $input = $this->_mangle_data($rule[2], $type, $operator);
+ $input = $this->_mangle_data($rule[2], $type, $operator);
$sql_match_operator = $operator['sql'];
switch ($rule[0]) {
case 'anywhere':
- $where[] = "(`artist`.`name` $sql_match_operator '$input' OR `album`.`name` $sql_match_operator '$input' OR `song_data`.`comment` $sql_match_operator '$input' OR `song_data`.`label` $sql_match_operator '$input' OR `song`.`file` $sql_match_operator '$input' OR `song`.`title` $sql_match_operator '$input')";
- $join['album'] = true;
- $join['artist'] = true;
+ $where[] = "(`artist`.`name` $sql_match_operator '$input' OR `album`.`name` $sql_match_operator '$input' OR `song_data`.`comment` $sql_match_operator '$input' OR `song_data`.`label` $sql_match_operator '$input' OR `song`.`file` $sql_match_operator '$input' OR `song`.`title` $sql_match_operator '$input')";
+ $join['album'] = true;
+ $join['artist'] = true;
$join['song_data'] = true;
break;
case 'tag':
- $key = md5($input . $sql_match_operator);
- $where[] = "`realtag_$key`.`match` > 0";
+ $key = md5($input . $sql_match_operator);
+ $where[] = "`realtag_$key`.`match` > 0";
$join['tag'][$key] = "$sql_match_operator '$input'";
break;
+ case 'album_tag':
+ $key = md5($input . $sql_match_operator);
+ $where[] = "`realtag_$key`.`match` > 0";
+ $join['album_tag'][$key] = "$sql_match_operator '$input'";
+ $join['album'] = true;
+ break;
case 'title':
$where[] = "`song`.`title` $sql_match_operator '$input'";
break;
case 'album':
- $where[] = "`album`.`name` $sql_match_operator '$input'";
+ $where[] = "`album`.`name` $sql_match_operator '$input'";
$join['album'] = true;
break;
case 'artist':
- $where[] = "`artist`.`name` $sql_match_operator '$input'";
+ $where[] = "`artist`.`name` $sql_match_operator '$input'";
$join['artist'] = true;
break;
case 'composer':
$where[] = "`song`.`composer` $sql_match_operator '$input'";
break;
case 'time':
- $input = $input * 60;
+ $input = $input * 60;
$where[] = "`song`.`time` $sql_match_operator '$input'";
break;
case 'file':
@@ -1210,26 +1240,26 @@ class Search extends playlist_object
$where[] = "`song`.`year` $sql_match_operator '$input'";
break;
case 'comment':
- $where[] = "`song_data`.`comment` $sql_match_operator '$input'";
+ $where[] = "`song_data`.`comment` $sql_match_operator '$input'";
$join['song_data'] = true;
break;
case 'label':
- $where[] = "`song_data`.`label` $sql_match_operator '$input'";
+ $where[] = "`song_data`.`label` $sql_match_operator '$input'";
$join['song_data'] = true;
break;
case 'played':
$where[] = " `song`.`played` = '$input'";
break;
case 'bitrate':
- $input = $input * 1000;
+ $input = $input * 1000;
$where[] = "`song`.`bitrate` $sql_match_operator '$input'";
break;
case 'rating':
if ($this->type != "public") {
$where[] = "COALESCE(`rating`.`rating`,0) $sql_match_operator '$input'";
} else {
- $group[] = "`song`.`id`";
- $having[] = "ROUND(AVG(`rating`.`rating`)) $sql_match_operator '$input'";
+ $group[] = "`song`.`id`";
+ $having[] = "ROUND(AVG(IFNULL(`rating`.`rating`,0))) $sql_match_operator '$input'";
}
$join['rating'] = true;
break;
@@ -1242,35 +1272,45 @@ class Search extends playlist_object
$where[] = "`song`.`catalog` $sql_match_operator '$input'";
break;
case 'playlist_name':
- $join['playlist'] = true;
+ $join['playlist'] = true;
$join['playlist_data'] = true;
- $where[] = "`playlist`.`name` $sql_match_operator '$input'";
+ $where[] = "`playlist`.`name` $sql_match_operator '$input'";
break;
case 'playlist':
$join['playlist_data'] = true;
- $where[] = "`playlist_data`.`playlist` $sql_match_operator '$input'";
+ $where[] = "`playlist_data`.`playlist` $sql_match_operator '$input'";
break;
case 'smartplaylist':
$subsearch = new Search($input, 'song');
- $subsql = $subsearch->to_sql();
- $where[] = "$sql_match_operator (" . $subsql['where_sql'] . ")";
+ $subsql = $subsearch->to_sql();
+ $where[] = "$sql_match_operator (" . $subsql['where_sql'] . ")";
// HACK: array_merge would potentially lose tags, since it
// overwrites. Save our merged tag joins in a temp variable,
// even though that's ugly.
- $tagjoin = array_merge($subsql['join']['tag'], $join['tag']);
- $join = array_merge($subsql['join'], $join);
+ $tagjoin = array_merge($subsql['join']['tag'], $join['tag']);
+ $join = array_merge($subsql['join'], $join);
$join['tag'] = $tagjoin;
break;
case 'license':
$where[] = "`song`.`license` $sql_match_operator '$input'";
break;
case 'added':
- $input = strtotime($input);
+ $input = strtotime($input);
$where[] = "`song`.`addition_time` $sql_match_operator $input";
break;
case 'updated':
- $input = strtotime($input);
+ $input = strtotime($input);
$where[] = "`song`.`update_time` $sql_match_operator $input";
+ break;
+ case 'metadata':
+ // Need to create a join for every field so we can create and / or queries with only one table
+ $tableAlias = 'metadata' . uniqid();
+ $field = (int) $rule[3];
+ $join[$tableAlias] = true;
+ $parsedInput = is_numeric($input) ? $input : '"' . $input . '"';
+ $where[] = "(`$tableAlias`.`field` = {$field} AND `$tableAlias`.`data` $sql_match_operator $parsedInput)";
+ $table[$tableAlias] = 'LEFT JOIN `metadata` AS ' . $tableAlias . ' ON `song`.`id` = `' . $tableAlias . '`.`object_id`';
+ break;
default:
// NOSSINK!
break;
@@ -1291,19 +1331,34 @@ class Search extends playlist_object
if ($join['song_data']) {
$table['song_data'] = "LEFT JOIN `song_data` ON `song`.`id`=`song_data`.`song_id`";
}
- foreach ($join['tag'] as $key => $value) {
- $table['tag_' . $key] =
- "LEFT JOIN (" .
- "SELECT `object_id`, COUNT(`name`) AS `match` ".
- "FROM `tag` LEFT JOIN `tag_map` " .
- "ON `tag`.`id`=`tag_map`.`tag_id` " .
- "WHERE `tag_map`.`object_type`='song' " .
- "AND `tag`.`name` $value GROUP BY `object_id`" .
- ") AS realtag_$key " .
- "ON `song`.`id`=`realtag_$key`.`object_id`";
+ if ($join['tag']) {
+ foreach ($join['tag'] as $key => $value) {
+ $table['tag_' . $key] =
+ "LEFT JOIN (" .
+ "SELECT `object_id`, COUNT(`name`) AS `match` " .
+ "FROM `tag` LEFT JOIN `tag_map` " .
+ "ON `tag`.`id`=`tag_map`.`tag_id` " .
+ "WHERE `tag_map`.`object_type`='song' " .
+ "AND `tag`.`name` $value GROUP BY `object_id`" .
+ ") AS realtag_$key " .
+ "ON `song`.`id`=`realtag_$key`.`object_id`";
+ }
+ }
+ if ($join['album_tag']) {
+ foreach ($join['album_tag'] as $key => $value) {
+ $table['tag_' . $key] =
+ "LEFT JOIN (" .
+ "SELECT `object_id`, COUNT(`name`) AS `match` " .
+ "FROM `tag` LEFT JOIN `tag_map` " .
+ "ON `tag`.`id`=`tag_map`.`tag_id` " .
+ "WHERE `tag_map`.`object_type`='album' " .
+ "AND `tag`.`name` $value GROUP BY `object_id`" .
+ ") AS realtag_$key " .
+ "ON `album`.`id`=`realtag_$key`.`object_id`";
+ }
}
if ($join['rating']) {
- $userid = $GLOBALS['user']->id;
+ $userid = $GLOBALS['user']->id;
$table['rating'] = "LEFT JOIN `rating` ON `rating`.`object_type`='song' AND ";
if ($this->type != "public") {
$table['rating'] .= "`rating`.`user`='$userid' AND ";
@@ -1322,8 +1377,8 @@ class Search extends playlist_object
$where_sql .= " AND `catalog_se`.`enabled` = '1'";
}
- $table_sql = implode(' ', $table);
- $group_sql = implode(', ', $group);
+ $table_sql = implode(' ', $table);
+ $group_sql = implode(', ', $group);
$having_sql = implode(" $sql_logic_operator ", $having);
return array(
@@ -1347,14 +1402,14 @@ class Search extends playlist_object
{
$sql_logic_operator = $this->logic_operator;
- $where = array();
- $table = array();
- $join = array();
- $group = array();
+ $where = array();
+ $table = array();
+ $join = array();
+ $group = array();
$having = array();
foreach ($this->rules as $rule) {
- $type = $this->name_to_basetype($rule[0]);
+ $type = $this->name_to_basetype($rule[0]);
$operator = array();
foreach ($this->basetypes[$type] as $op) {
if ($op['name'] == $rule[1]) {
@@ -1362,7 +1417,7 @@ class Search extends playlist_object
break;
}
}
- $input = $this->_mangle_data($rule[2], $type, $operator);
+ $input = $this->_mangle_data($rule[2], $type, $operator);
$sql_match_operator = $operator['sql'];
switch ($rule[0]) {
@@ -1383,8 +1438,8 @@ class Search extends playlist_object
$where_sql .= " AND `catalog_se`.`enabled` = '1'";
}
- $table_sql = implode(' ', $table);
- $group_sql = implode(', ', $group);
+ $table_sql = implode(' ', $table);
+ $group_sql = implode(', ', $group);
$having_sql = implode(" $sql_logic_operator ", $having);
return array(
@@ -1407,14 +1462,14 @@ class Search extends playlist_object
private function playlist_to_sql()
{
$sql_logic_operator = $this->logic_operator;
- $where = array();
- $table = array();
- $join = array();
- $group = array();
- $having = array();
+ $where = array();
+ $table = array();
+ $join = array();
+ $group = array();
+ $having = array();
foreach ($this->rules as $rule) {
- $type = $this->name_to_basetype($rule[0]);
+ $type = $this->name_to_basetype($rule[0]);
$operator = array();
foreach ($this->basetypes[$type] as $op) {
if ($op['name'] == $rule[1]) {
@@ -1422,7 +1477,7 @@ class Search extends playlist_object
break;
}
}
- $input = $this->_mangle_data($rule[2], $type, $operator);
+ $input = $this->_mangle_data($rule[2], $type, $operator);
$sql_match_operator = $operator['sql'];
$where[] = "`playlist`.`type` = 'public'";
@@ -1438,8 +1493,8 @@ class Search extends playlist_object
} // foreach rule
$join['playlist_data'] = true;
- $join['song'] = $join['song'] || AmpConfig::get('catalog_disable');
- $join['catalog'] = AmpConfig::get('catalog_disable');
+ $join['song'] = $join['song'] || AmpConfig::get('catalog_disable');
+ $join['catalog'] = AmpConfig::get('catalog_disable');
$where_sql = implode(" $sql_logic_operator ", $where);
@@ -1457,8 +1512,8 @@ class Search extends playlist_object
}
}
- $table_sql = implode(' ', $table);
- $group_sql = implode(', ', $group);
+ $table_sql = implode(' ', $table);
+ $group_sql = implode(', ', $group);
$having_sql = implode(" $sql_logic_operator ", $having);
return array(
@@ -1481,11 +1536,11 @@ class Search extends playlist_object
private function label_to_sql()
{
$sql_logic_operator = $this->logic_operator;
- $where = array();
- $table = array();
+ $where = array();
+ $table = array();
foreach ($this->rules as $rule) {
- $type = $this->name_to_basetype($rule[0]);
+ $type = $this->name_to_basetype($rule[0]);
$operator = array();
foreach ($this->basetypes[$type] as $op) {
if ($op['name'] == $rule[1]) {
@@ -1493,7 +1548,7 @@ class Search extends playlist_object
break;
}
}
- $input = $this->_mangle_data($rule[2], $type, $operator);
+ $input = $this->_mangle_data($rule[2], $type, $operator);
$sql_match_operator = $operator['sql'];
switch ($rule[0]) {
@@ -1531,11 +1586,11 @@ class Search extends playlist_object
private function user_to_sql()
{
$sql_logic_operator = $this->logic_operator;
- $where = array();
- $table = array();
+ $where = array();
+ $table = array();
foreach ($this->rules as $rule) {
- $type = $this->name_to_basetype($rule[0]);
+ $type = $this->name_to_basetype($rule[0]);
$operator = array();
foreach ($this->basetypes[$type] as $op) {
if ($op['name'] == $rule[1]) {
@@ -1543,7 +1598,7 @@ class Search extends playlist_object
break;
}
}
- $input = $this->_mangle_data($rule[2], $type, $operator);
+ $input = $this->_mangle_data($rule[2], $type, $operator);
$sql_match_operator = $operator['sql'];
switch ($rule[0]) {
diff --git a/sources/lib/class/session.class.php b/sources/lib/class/session.class.php
index 7c694ac..0c83cf9 100644
--- a/sources/lib/class/session.class.php
+++ b/sources/lib/class/session.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -68,7 +68,7 @@ class Session
}
$expire = time() + AmpConfig::get('session_length');
- $sql = 'UPDATE `session` SET `value` = ?, `expire` = ? WHERE `id` = ?';
+ $sql = 'UPDATE `session` SET `value` = ?, `expire` = ? WHERE `id` = ?';
Dba::write($sql, array($value, $expire, $key));
debug_event('session', 'Writing to ' . $key . ' with expiration ' . $expire, 6);
@@ -83,7 +83,9 @@ class Session
*/
public static function destroy($key)
{
- if (!strlen($key)) { return false; }
+ if (!strlen($key)) {
+ return false;
+ }
// Remove anything and EVERYTHING
$sql = 'DELETE FROM `session` WHERE `id` = ?';
@@ -91,8 +93,8 @@ class Session
debug_event('SESSION', 'Deleting Session with key:' . $key, 6);
- $session_name = AmpConfig::get('session_name');
- $cookie_path = AmpConfig::get('cookie_path');
+ $session_name = AmpConfig::get('session_name');
+ $cookie_path = AmpConfig::get('cookie_path');
$cookie_domain = null;
$cookie_secure = AmpConfig::get('cookie_secure');
@@ -142,7 +144,7 @@ class Session
*/
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()));
if ($results = Dba::fetch_assoc($db_results)) {
@@ -204,8 +206,8 @@ class Session
if (isset($data['username'])) {
$username = $data['username'];
}
- $ip = $_SERVER['REMOTE_ADDR'] ? inet_pton($_SERVER['REMOTE_ADDR']) : '0';
- $type = $data['type'];
+ $ip = $_SERVER['REMOTE_ADDR'] ? inet_pton($_SERVER['REMOTE_ADDR']) : '0';
+ $type = $data['type'];
$value = '';
if (isset($data['value'])) {
$value = $data['value'];
@@ -231,7 +233,9 @@ class Session
$geoname = $data['geo_name'];
}
- if (!strlen($value)) { $value = ' '; }
+ if (!strlen($value)) {
+ $value = ' ';
+ }
/* Insert the row */
$sql = 'INSERT INTO `session` (`id`,`username`,`ip`,`type`,`agent`,`value`,`expire`,`geo_latitude`,`geo_longitude`, `geo_name`) ' .
@@ -259,7 +263,9 @@ class Session
$session_name = AmpConfig::get('session_name');
// No cookie no go!
- if (!isset($_COOKIE[$session_name])) { return false; }
+ if (!isset($_COOKIE[$session_name])) {
+ return false;
+ }
// Set up the cookie params before we start the session.
// This is vital
@@ -304,7 +310,7 @@ class Session
$sql = 'SELECT * FROM `session` WHERE `id` = ? AND `expire` > ?';
if (AmpConfig::get('use_auth')) {
// Build a list of enabled authentication types
- $types = AmpConfig::get('auth_methods');
+ $types = AmpConfig::get('auth_methods');
$enabled_types = implode("','", $types);
$sql .= " AND `type` IN('$enabled_types')";
}
@@ -383,12 +389,12 @@ class Session
$location = array();
if ($sid) {
- $sql = "SELECT `geo_latitude`, `geo_longitude`, `geo_name` FROM `session` WHERE `id` = ?";
+ $sql = "SELECT `geo_latitude`, `geo_longitude`, `geo_name` FROM `session` WHERE `id` = ?";
$db_results = Dba::read($sql, array($sid));
if ($row = Dba::fetch_assoc($db_results)) {
- $location['latitude'] = $row['geo_latitude'];
+ $location['latitude'] = $row['geo_latitude'];
$location['longitude'] = $row['geo_longitude'];
- $location['name'] = $row['geo_name'];
+ $location['name'] = $row['geo_name'];
}
}
@@ -432,8 +438,8 @@ class Session
public static function create_cookie()
{
// Set up the cookie prefs before we throw down, this is very important
- $cookie_life = AmpConfig::get('cookie_life');
- $cookie_path = AmpConfig::get('cookie_path');
+ $cookie_life = AmpConfig::get('cookie_life');
+ $cookie_path = AmpConfig::get('cookie_path');
$cookie_domain = null;
$cookie_secure = AmpConfig::get('cookie_secure');
@@ -454,9 +460,9 @@ class Session
*/
public static function create_user_cookie($username)
{
- $cookie_life = AmpConfig::get('cookie_life');
- $session_name = AmpConfig::get('session_name');
- $cookie_path = AmpConfig::get('cookie_path');
+ $cookie_life = AmpConfig::get('cookie_life');
+ $session_name = AmpConfig::get('session_name');
+ $cookie_path = AmpConfig::get('cookie_path');
$cookie_domain = null;
$cookie_secure = AmpConfig::get('cookie_secure');
@@ -471,12 +477,12 @@ class Session
public static function create_remember_cookie($username)
{
$remember_length = AmpConfig::get('remember_length');
- $session_name = AmpConfig::get('session_name');
+ $session_name = AmpConfig::get('session_name');
$token = self::generateRandomToken(); // generate a token, should be 128 - 256 bit
self::storeTokenForUser($username, $token, $remember_length);
$cookie = $username . ':' . $token;
- $mac = hash_hmac('sha256', $cookie, AmpConfig::get('secret_key'));
+ $mac = hash_hmac('sha256', $cookie, AmpConfig::get('secret_key'));
$cookie .= ':' . $mac;
setcookie($session_name . '_remember', $cookie, time() + $remember_length);
@@ -499,12 +505,12 @@ class Session
public static function auth_remember()
{
- $auth = false;
+ $auth = false;
$cname = AmpConfig::get('session_name') . '_remember';
if (isset($_COOKIE[$cname])) {
list ($username, $token, $mac) = explode(':', $_COOKIE[$cname]);
if ($mac === hash_hmac('sha256', $username . ':' . $token, AmpConfig::get('secret_key'))) {
- $sql = "SELECT * FROM `session_remember` WHERE `username` = ? AND `token` = ? AND `expire` >= ?";
+ $sql = "SELECT * FROM `session_remember` WHERE `username` = ? AND `token` = ? AND `expire` >= ?";
$db_results = Dba::read($sql, array($username, $token, time()));
if (Dba::num_rows($db_results) > 0) {
Session::create_cookie();
@@ -513,7 +519,7 @@ class Session
'username' => $username
));
$_SESSION['userdata']['username'] = $username;
- $auth = true;
+ $auth = true;
}
}
}
@@ -541,5 +547,4 @@ class Session
return true;
}
-
}
diff --git a/sources/lib/class/share.class.php b/sources/lib/class/share.class.php
index 2331560..ba98fb6 100644
--- a/sources/lib/class/share.class.php
+++ b/sources/lib/class/share.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -50,7 +50,9 @@ class Share extends database_object
*/
public function __construct($id=0)
{
- if (!$id) { return true; }
+ if (!$id) {
+ return true;
+ }
/* Get the information from the db */
$info = $this->get_info($id);
@@ -65,7 +67,7 @@ class Share extends database_object
public static function delete_share($id)
{
- $sql = "DELETE FROM `share` WHERE `id` = ?";
+ $sql = "DELETE FROM `share` WHERE `id` = ?";
$params = array( $id );
if (!$GLOBALS['user']->has_access('75')) {
$sql .= " AND `user` = ?";
@@ -91,7 +93,7 @@ class Share extends database_object
public static function generate_secret($length = 8)
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
- $secret = '';
+ $secret = '';
for ($i = 0; $i < $length; $i++) {
$secret .= $characters[rand(0, strlen($characters) - 1)];
}
@@ -115,11 +117,15 @@ class Share extends database_object
public static function create_share($object_type, $object_id, $allow_stream=true, $allow_download=true, $expire=0, $secret='', $max_counter=0, $description='')
{
$object_type = self::format_type($object_type);
- if (empty($object_type)) return '';
+ if (empty($object_type)) {
+ return '';
+ }
- if (!$allow_stream && !$allow_download) return '';
+ if (!$allow_stream && !$allow_download) {
+ return '';
+ }
- $sql = "INSERT INTO `share` (`user`, `object_type`, `object_id`, `creation_date`, `allow_stream`, `allow_download`, `expire_days`, `secret`, `counter`, `max_counter`, `description`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
+ $sql = "INSERT INTO `share` (`user`, `object_type`, `object_id`, `creation_date`, `allow_stream`, `allow_download`, `expire_days`, `secret`, `counter`, `max_counter`, `description`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$params = array($GLOBALS['user']->id, $object_type, $object_id, time(), $allow_stream ?: 0, $allow_download ?: 0, $expire, $secret, 0, $max_counter, $description);
Dba::write($sql, $params);
@@ -170,9 +176,9 @@ class Share extends database_object
public static function get_share_list()
{
- $sql = self::get_share_list_sql();
+ $sql = self::get_share_list_sql();
$db_results = Dba::read($sql);
- $results = array();
+ $results = array();
while ($row = Dba::fetch_assoc($db_results)) {
$results[] = $row['id'];
@@ -183,9 +189,9 @@ class Share extends database_object
public static function get_shares($object_type, $object_id)
{
- $sql = "SELECT `id` FROM `share` WHERE `object_type` = ? AND `object_id` = ?";
+ $sql = "SELECT `id` FROM `share` WHERE `object_type` = ? AND `object_id` = ?";
$db_results = Dba::read($sql, array($object_type, $object_id));
- $results = array();
+ $results = array();
while ($row = Dba::fetch_assoc($db_results)) {
$results[] = $row['id'];
}
@@ -197,8 +203,8 @@ class Share extends database_object
{
if ($this->id) {
if ($GLOBALS['user']->has_access('75') || $this->user == $GLOBALS['user']->id) {
- echo "id ."\" onclick=\"showEditDialog('share_row', '" . $this->id . "', 'edit_share_" . $this->id . "', '" . T_('Share edit') . "', 'share_')\">" . UI::get_icon('edit', T_('Edit')) . "";
- echo "id ."\">" . UI::get_icon('delete', T_('Delete')) . "";
+ echo "id . "\" onclick=\"showEditDialog('share_row', '" . $this->id . "', 'edit_share_" . $this->id . "', '" . T_('Share edit') . "', 'share_')\">" . UI::get_icon('edit', T_('Edit')) . "";
+ echo "id . "\">" . UI::get_icon('delete', T_('Delete')) . "";
}
}
}
@@ -208,25 +214,25 @@ class Share extends database_object
if ($details) {
$object = new $this->object_type($this->object_id);
$object->format();
- $this->f_name = $object->get_fullname();
+ $this->f_name = $object->get_fullname();
$this->f_object_link = $object->f_link;
- $user = new User($this->user);
+ $user = new User($this->user);
$user->format();
$this->f_user = $user->f_name;
}
- $this->f_allow_stream = $this->allow_stream;
+ $this->f_allow_stream = $this->allow_stream;
$this->f_allow_download = $this->allow_download;
- $this->f_creation_date = date("Y-m-d H:i:s", $this->creation_date);
+ $this->f_creation_date = date("Y-m-d H:i:s", $this->creation_date);
$this->f_lastvisit_date = ($this->lastvisit_date > 0) ? date("Y-m-d H:i:s", $this->creation_date) : '';
}
public function update(array $data)
{
- $this->max_counter = intval($data['max_counter']);
- $this->expire_days = intval($data['expire']);
- $this->allow_stream = $data['allow_stream'] == '1';
+ $this->max_counter = intval($data['max_counter']);
+ $this->expire_days = intval($data['expire']);
+ $this->allow_stream = $data['allow_stream'] == '1';
$this->allow_download = $data['allow_download'] == '1';
- $this->description = isset($data['description']) ? $data['description'] : $this->description;
+ $this->description = isset($data['description']) ? $data['description'] : $this->description;
$sql = "UPDATE `share` SET `max_counter` = ?, `expire_days` = ?, `allow_stream` = ?, `allow_download` = ?, `description` = ? " .
"WHERE `id` = ?";
@@ -288,13 +294,13 @@ class Share extends database_object
public function create_fake_playlist()
{
$playlist = new Stream_Playlist(-1);
- $medias = array();
+ $medias = array();
switch ($this->object_type) {
case 'album':
case 'playlist':
$object = new $this->object_type($this->object_id);
- $songs = $object->get_medias('song');
+ $songs = $object->get_medias('song');
foreach ($songs as $song) {
$medias[] = $song;
}
@@ -318,10 +324,12 @@ class Share extends database_object
case 'album':
case 'playlist':
$object = new $this->object_type($this->object_id);
- $songs = $object->get_songs();
+ $songs = $object->get_songs();
foreach ($songs as $id) {
$is_shared = ($media_id == $id);
- if ($is_shared) { break; }
+ if ($is_shared) {
+ break;
+ }
}
break;
default:
@@ -349,7 +357,7 @@ class Share extends database_object
public static function display_ui_links($object_type, $object_id)
{
echo "
";
}
-
} // end of recommendation class
+
diff --git a/sources/lib/class/shoutbox.class.php b/sources/lib/class/shoutbox.class.php
index d80b80c..8a229c5 100644
--- a/sources/lib/class/shoutbox.class.php
+++ b/sources/lib/class/shoutbox.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -46,7 +46,6 @@ class Shoutbox
$this->_get_info($shout_id);
return true;
-
} // Constructor
/**
@@ -55,7 +54,7 @@ class Shoutbox
*/
private function _get_info($shout_id)
{
- $sql = "SELECT * FROM `user_shout` WHERE `id` = ?";
+ $sql = "SELECT * FROM `user_shout` WHERE `id` = ?";
$db_results = Dba::read($sql, array($shout_id));
$data = Dba::fetch_assoc($db_results);
@@ -65,7 +64,6 @@ class Shoutbox
}
return true;
-
} // _get_info
/**
@@ -107,9 +105,9 @@ class Shoutbox
}
// Only get as many as we need
- $limit = intval($limit) - count($shouts);
+ $limit = intval($limit) - count($shouts);
$params = array();
- $sql = "SELECT `user_shout`.`id` AS `id` FROM `user_shout` LEFT JOIN `user` ON `user`.`id` = `user_shout`.`user` WHERE `user_shout`.`sticky`='0' ";
+ $sql = "SELECT `user_shout`.`id` AS `id` FROM `user_shout` LEFT JOIN `user` ON `user`.`id` = `user_shout`.`user` WHERE `user_shout`.`sticky`='0' ";
if ($username !== null) {
$sql .= "AND `user`.`username` = ? ";
$params[] = $username;
@@ -122,12 +120,11 @@ class Shoutbox
}
return $shouts;
-
} // get_top
public static function get_shouts_since($time)
{
- $sql = "SELECT * FROM `user_shout` WHERE `date` > ? ORDER BY `date` DESC";
+ $sql = "SELECT * FROM `user_shout` WHERE `date` > ? ORDER BY `date` DESC";
$db_results = Dba::read($sql, array($time));
$shouts = array();
@@ -136,7 +133,6 @@ class Shoutbox
}
return $shouts;
-
}
/**
@@ -145,7 +141,7 @@ class Shoutbox
*/
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);
$results = array();
@@ -155,7 +151,6 @@ class Shoutbox
}
return $results;
-
} // get_sticky
/**
@@ -164,13 +159,23 @@ class Shoutbox
*/
public static function get_object($type,$object_id)
{
- if (!Core::is_library_item($type))
+ if (!Core::is_library_item($type)) {
return false;
+ }
$object = new $type($object_id);
+
+ if ($object->id > 0) {
+ if (strtolower($type) === 'song') {
+ if (!$object->enabled) {
+ $object = null;
+ }
+ }
+ } else {
+ $object = null;
+ }
return $object;
-
} // get_object
/**
@@ -186,7 +191,6 @@ class Shoutbox
}
return $image_string;
-
} // get_image
/**
@@ -195,8 +199,9 @@ class Shoutbox
*/
public static function create(array $data)
{
- if (!Core::is_library_item($data['object_type']))
+ if (!Core::is_library_item($data['object_type'])) {
return false;
+ }
$sticky = isset($data['sticky']) ? 1 : 0;
$user = intval($data['user'] ?: $GLOBALS['user']->id);
@@ -206,12 +211,14 @@ class Shoutbox
$sql = "INSERT INTO `user_shout` (`user`,`date`,`text`,`sticky`,`object_id`,`object_type`, `data`) " .
"VALUES (? , ?, ?, ?, ?, ?, ?)";
Dba::write($sql, array($user, $date, $comment, $sticky, $data['object_id'], $data['object_type'], $data['data']));
+
+ Useractivity::post_activity($user, 'shout', $data['object_type'], $data['object_id']);
$insert_id = Dba::insert_id();
// Never send email in case of user impersonation
if (!isset($data['user']) && $insert_id) {
- $libitem = new $data['object_type']($data['object_id']);
+ $libitem = new $data['object_type']($data['object_id']);
$item_owner_id = $libitem->get_user_owner();
if ($item_owner_id) {
if (Preference::get_by_user($item_owner_id, 'notify_email')) {
@@ -220,10 +227,10 @@ class Shoutbox
$libitem->format();
$mailer = new Mailer();
$mailer->set_default_sender();
- $mailer->recipient = $item_owner->email;
+ $mailer->recipient = $item_owner->email;
$mailer->recipient_name = $item_owner->fullname;
- $mailer->subject = T_('New shout on your content');
- $mailer->message = sprintf(T_("You just received a new shout from %s on your content `%s`.\n\n
+ $mailer->subject = T_('New shout on your content');
+ $mailer->message = sprintf(T_("You just received a new shout from %s on your content `%s`.\n\n
----------------------
%s
----------------------
@@ -237,7 +244,6 @@ class Shoutbox
}
return $insert_id;
-
} // create
/**
@@ -250,7 +256,6 @@ class Shoutbox
Dba::write($sql, array($data['comment'], make_bool($data['sticky']), $this->id));
return $this->id;
-
} // create
/**
@@ -264,7 +269,6 @@ class Shoutbox
$this->f_date = date("m\/d\/Y - H:i", $this->date);
$this->f_text = preg_replace('/(\r\n|\n|\r)/', ' ', $this->text);
return true;
-
} //format
/**
@@ -276,16 +280,15 @@ class Shoutbox
{
// Delete the shoutbox post
$shout_id = Dba::escape($shout_id);
- $sql = "DELETE FROM `user_shout` WHERE `id`='$shout_id'";
+ $sql = "DELETE FROM `user_shout` WHERE `id`='$shout_id'";
Dba::write($sql);
-
} // delete
public function get_display($details = true, $jsbuttons = false)
{
$object = Shoutbox::get_object($this->object_type, $this->object_id);
$object->format();
- $img = $this->get_image();
+ $img = $this->get_image();
$html = "
";
$html .= "
";
if ($details && $img) {
@@ -294,7 +297,7 @@ class Shoutbox
$html .= "
";
if ($details) {
$html .= "
" . $object->f_link . "
";
- $html .= "
".date("Y/m/d H:i:s", $this->date) . "
";
+ $html .= "
" . date("Y/m/d H:i:s", $this->date) . "
";
}
$html .= "
" . $this->f_text . "
";
$html .= "
";
@@ -303,8 +306,8 @@ class Shoutbox
if ($details) {
$html .= "
";
if ($jsbuttons) {
- $html .= Ajax::button('?page=stream&action=directplay&playtype=' . $this->object_type .'&' . $this->object_type . '_id=' . $this->object_id,'play', T_('Play'),'play_' . $this->object_type . '_' . $this->object_id);
- $html .= Ajax::button('?action=basket&type=' . $this->object_type .'&id=' . $this->object_id,'add', T_('Add'),'add_' . $this->object_type . '_' . $this->object_id);
+ $html .= Ajax::button('?page=stream&action=directplay&playtype=' . $this->object_type . '&' . $this->object_type . '_id=' . $this->object_id,'play', T_('Play'),'play_' . $this->object_type . '_' . $this->object_id);
+ $html .= Ajax::button('?action=basket&type=' . $this->object_type . '&id=' . $this->object_id,'add', T_('Add'),'add_' . $this->object_type . '_' . $this->object_id);
}
if (Access::check('interface','25')) {
$html .= "object_type . "&id=" . $this->object_id . "\">" . UI::get_icon('comment', T_('Post Shout')) . "";
@@ -333,9 +336,9 @@ class Shoutbox
public static function get_shouts($object_type, $object_id)
{
- $sql = "SELECT `id` FROM `user_shout` WHERE `object_type` = ? AND `object_id` = ? ORDER BY `sticky`, `date` DESC";
+ $sql = "SELECT `id` FROM `user_shout` WHERE `object_type` = ? AND `object_id` = ? ORDER BY `sticky`, `date` DESC";
$db_results = Dba::read($sql, array($object_type, $object_id));
- $results = array();
+ $results = array();
while ($row = Dba::fetch_assoc($db_results)) {
$results[] = $row['id'];
@@ -343,5 +346,5 @@ class Shoutbox
return $results;
}
-
} // Shoutbox class
+
diff --git a/sources/lib/class/slideshow.class.php b/sources/lib/class/slideshow.class.php
index ad73742..c053261 100644
--- a/sources/lib/class/slideshow.class.php
+++ b/sources/lib/class/slideshow.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -24,7 +24,7 @@ class Slideshow
{
public static function get_current_slideshow()
{
- $songs = Song::get_recently_played($GLOBALS['user']->id);
+ $songs = Song::get_recently_played($GLOBALS['user']->id);
$images = array();
if (count($songs) > 0) {
$last_song = new Song($songs[0]['object_id']);
@@ -58,5 +58,5 @@ class Slideshow
return $images;
}
-
} // end of Slideshow class
+
diff --git a/sources/lib/class/song.class.php b/sources/lib/class/song.class.php
index e4cfc98..e924eac 100644
--- a/sources/lib/class/song.class.php
+++ b/sources/lib/class/song.class.php
@@ -2,26 +2,28 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
class Song extends database_object implements media, library_item
{
+ use \Lib\Metadata\Metadata;
+
/* Variables from DB */
/**
@@ -285,6 +287,16 @@ class Song extends database_object implements media, library_item
*/
public $_fake = false; // If this is a 'construct_from_array' object
+ /**
+ * Aliases used in insert function
+ */
+ public static $aliases = array(
+ 'mb_trackid','mbid','mb_albumid','mb_albumid_group','mb_artistid','mb_albumartistid','genre','publisher'
+ );
+
+
+
+
/**
* Constructor
*
@@ -293,15 +305,21 @@ class Song extends database_object implements media, library_item
*/
public function __construct($id = null, $limit_threshold = '')
{
- if (!$id) { return false; }
+ if (!$id) {
+ return false;
+ }
$this->id = intval($id);
+ if (self::isCustomMetadataEnabled()) {
+ $this->initializeMetadata();
+ }
+
if ($info = $this->_get_info($limit_threshold)) {
foreach ($info as $key => $value) {
$this->$key = $value;
}
- $data = pathinfo($this->file);
+ $data = pathinfo($this->file);
$this->type = strtolower($data['extension']);
$this->mime = self::type_to_mime($this->type);
} else {
@@ -310,7 +328,6 @@ class Song extends database_object implements media, library_item
}
return true;
-
} // constructor
/**
@@ -322,38 +339,38 @@ class Song extends database_object implements media, library_item
*/
public static function insert(array $results)
{
- $catalog = $results['catalog'];
- $file = $results['file'];
- $title = trim($results['title']) ?: $file;
- $artist = $results['artist'];
- $album = $results['album'];
- $albumartist = $results['albumartist'] ?: $results['band'];
- $albumartist = $albumartist ?: null;
- $bitrate = $results['bitrate'] ?: 0;
- $rate = $results['rate'] ?: 0;
- $mode = $results['mode'];
- $size = $results['size'] ?: 0;
- $time = $results['time'] ?: 0;
- $track = $results['track'];
- $track_mbid = $results['mb_trackid'] ?: $results['mbid'];
- $track_mbid = $track_mbid ?: null;
- $album_mbid = $results['mb_albumid'];
- $album_mbid_group = $results['mb_albumid_group'];
- $artist_mbid = $results['mb_artistid'];
- $albumartist_mbid = $results['mb_albumartistid'];
- $disk = $results['disk'] ?: 0;
- $year = $results['year'] ?: 0;
- $comment = $results['comment'];
- $tags = $results['genre']; // multiple genre support makes this an array
- $lyrics = $results['lyrics'];
- $user_upload = isset($results['user_upload']) ? $results['user_upload'] : null;
- $license = isset($results['license']) ? $results['license'] : null;
- $composer = isset($results['composer']) ? $results['composer'] : null;
- $label = isset($results['publisher']) ? $results['publisher'] : null;
- $catalog_number = isset($results['catalog_number']) ? $results['catalog_number'] : null;
- $language = isset($results['language']) ? $results['language'] : null;
- $channels = $results['channels'] ?: 0;
- $release_type = isset($results['release_type']) ? $results['release_type'] : null;
+ $catalog = $results['catalog'];
+ $file = $results['file'];
+ $title = trim($results['title']) ?: $file;
+ $artist = $results['artist'];
+ $album = $results['album'];
+ $albumartist = $results['albumartist'] ?: $results['band'];
+ $albumartist = $albumartist ?: null;
+ $bitrate = $results['bitrate'] ?: 0;
+ $rate = $results['rate'] ?: 0;
+ $mode = $results['mode'];
+ $size = $results['size'] ?: 0;
+ $time = $results['time'] ?: 0;
+ $track = $results['track'];
+ $track_mbid = $results['mb_trackid'] ?: $results['mbid'];
+ $track_mbid = $track_mbid ?: null;
+ $album_mbid = $results['mb_albumid'];
+ $album_mbid_group = $results['mb_albumid_group'];
+ $artist_mbid = $results['mb_artistid'];
+ $albumartist_mbid = $results['mb_albumartistid'];
+ $disk = $results['disk'] ?: 0;
+ $year = Catalog::normalize_year($results['year'] ?: 0);
+ $comment = $results['comment'];
+ $tags = $results['genre']; // multiple genre support makes this an array
+ $lyrics = $results['lyrics'];
+ $user_upload = isset($results['user_upload']) ? $results['user_upload'] : null;
+ $license = isset($results['license']) ? $results['license'] : null;
+ $composer = isset($results['composer']) ? $results['composer'] : null;
+ $label = isset($results['publisher']) ? $results['publisher'] : null;
+ $catalog_number = isset($results['catalog_number']) ? $results['catalog_number'] : null;
+ $language = isset($results['language']) ? $results['language'] : null;
+ $channels = $results['channels'] ?: 0;
+ $release_type = isset($results['release_type']) ? $results['release_type'] : null;
$replaygain_track_gain = isset($results['replaygain_track_gain']) ? $results['replaygain_track_gain'] : null;
$replaygain_track_peak = isset($results['replaygain_track_peak']) ? $results['replaygain_track_peak'] : null;
$replaygain_album_gain = isset($results['replaygain_album_gain']) ? $results['replaygain_album_gain'] : null;
@@ -398,6 +415,10 @@ class Song extends database_object implements media, library_item
}
$song_id = Dba::insert_id();
+
+ if ($user_upload) {
+ Useractivity::post_activity($this->id, 'upload', 'song', $song_id);
+ }
if (is_array($tags)) {
// Allow scripts to populate new tags when injecting user uploads
@@ -444,18 +465,22 @@ class Song extends database_object implements media, library_item
*/
public static function build_cache($song_ids, $limit_threshold = '')
{
- if (!is_array($song_ids) || !count($song_ids)) { return false; }
+ if (!is_array($song_ids) || !count($song_ids)) {
+ return false;
+ }
$idlist = '(' . implode(',', $song_ids) . ')';
// Callers might have passed array(false) because they are dumb
- if ($idlist == '()') { return false; }
+ if ($idlist == '()') {
+ return false;
+ }
// Song data cache
$sql = 'SELECT `song`.`id`, `file`, `catalog`, `album`, ' .
'`year`, `artist`, `title`, `bitrate`, `rate`, ' .
'`mode`, `size`, `time`, `track`, `played`, ' .
- '`song`.`enabled`, `update_time`, `tag_map`.`tag_id`, '.
+ '`song`.`enabled`, `update_time`, `tag_map`.`tag_id`, ' .
'`mbid`, `addition_time`, `license`, `composer`, `user_upload` ' .
'FROM `song` LEFT JOIN `tag_map` ' .
'ON `tag_map`.`object_id`=`song`.`id` ' .
@@ -470,8 +495,8 @@ class Song extends database_object implements media, library_item
$db_results = Dba::read($sql);
$artists = array();
- $albums = array();
- $tags = array();
+ $albums = array();
+ $tags = array();
while ($row = Dba::fetch_assoc($db_results)) {
if (AmpConfig::get('show_played_times')) {
@@ -479,7 +504,7 @@ class Song extends database_object implements media, library_item
}
parent::add_to_cache('song', $row['id'], $row);
$artists[$row['artist']] = $row['artist'];
- $albums[$row['album']] = $row['album'];
+ $albums[$row['album']] = $row['album'];
if ($row['tag_id']) {
$tags[$row['tag_id']] = $row['tag_id'];
}
@@ -500,7 +525,7 @@ class Song extends database_object implements media, library_item
}
// Build a cache for the song's extended table
- $sql = "SELECT * FROM `song_data` WHERE `song_id` IN $idlist";
+ $sql = "SELECT * FROM `song_data` WHERE `song_id` IN $idlist";
$db_results = Dba::read($sql);
while ($row = Dba::fetch_assoc($db_results)) {
@@ -508,7 +533,6 @@ class Song extends database_object implements media, library_item
}
return true;
-
} // build_cache
/**
@@ -559,7 +583,7 @@ class Song extends database_object implements media, library_item
return parent::get_from_cache('song_data',$id);
}
- $sql = "SELECT * FROM song_data WHERE `song_id` = ?";
+ $sql = "SELECT * FROM song_data WHERE `song_id` = ?";
$db_results = Dba::read($sql, array($id));
$results = Dba::fetch_assoc($db_results);
@@ -567,7 +591,6 @@ class Song extends database_object implements media, library_item
parent::add_to_cache('song_data',$id,$results);
return $results;
-
} // _get_ext_info
/**
@@ -583,7 +606,6 @@ class Song extends database_object implements media, library_item
$this->$key = $value;
}
} // end foreach
-
} // fill_ext_info
/**
@@ -602,6 +624,8 @@ class Song extends database_object implements media, library_item
case 'spx':
case 'ogg':
return 'application/ogg';
+ case 'opus':
+ return 'audio/ogg; codecs=opus';
case 'wma':
case 'asf':
return 'audio/x-ms-wma';
@@ -642,7 +666,9 @@ class Song extends database_object implements media, library_item
$results = array();
$sql = "SELECT `id` FROM `song` WHERE `enabled`='0'";
- if ($count) { $sql .= " LIMIT $count"; }
+ if ($count) {
+ $sql .= " LIMIT $count";
+ }
$db_results = Dba::read($sql);
while ($r = Dba::fetch_assoc($db_results)) {
@@ -662,10 +688,10 @@ class Song extends database_object implements media, library_item
*/
public static function find_duplicates($search_type)
{
- $where_sql = $_REQUEST['search_disabled'] ? '' : "WHERE `enabled` != '0'";
- $sql = 'SELECT `id`, `artist`, `album`, `title`, ' .
+ $where_sql = $_REQUEST['search_disabled'] ? '' : "WHERE `enabled` != '0'";
+ $sql = 'SELECT `id`, `artist`, `album`, `title`, ' .
'COUNT(`title`) FROM `song` ' . $where_sql .
- ' GROUP BY `title`';
+ ' GROUP BY `id`, `artist`, `album`, `title`';
if ($search_type == 'artist_title' ||
$search_type == 'artist_album_title') {
@@ -696,25 +722,28 @@ class Song extends database_object implements media, library_item
*/
public static function get_duplicate_info($dupe, $search_type)
{
- $sql = 'SELECT `id` FROM `song` ' .
- "WHERE `title`='" . Dba::escape($dupe['title']) . "' ";
-
- if ($search_type == 'artist_title' ||
- $search_type == 'artist_album_title') {
- $sql .= "AND `artist`='" . Dba::escape($dupe['artist']) . "' ";
- }
- if ($search_type == 'artist_album_title') {
- $sql .= "AND `album` = '" . Dba::escape($dupe['album']) . "' ";
- }
-
- $sql .= 'ORDER BY `time`,`bitrate`,`size`';
- $db_results = Dba::read($sql);
-
$results = array();
+ if (isset($dupe['id'])) {
+ $results[] = $dupe['id'];
+ } else {
+ $sql = "SELECT `id` FROM `song` WHERE " .
+ "`title`='" . Dba::escape($dupe['title']) . "' ";
- while ($item = Dba::fetch_assoc($db_results)) {
- $results[] = $item['id'];
- } // end while
+ if ($search_type == 'artist_title' ||
+ $search_type == 'artist_album_title') {
+ $sql .= "AND `artist`='" . Dba::escape($dupe['artist']) . "' ";
+ }
+ if ($search_type == 'artist_album_title') {
+ $sql .= "AND `album` = '" . Dba::escape($dupe['album']) . "' ";
+ }
+
+ $sql .= 'ORDER BY `time`,`bitrate`,`size`';
+ $db_results = Dba::read($sql);
+
+ while ($item = Dba::fetch_assoc($db_results)) {
+ $results[] = $item['id'];
+ } // end while
+ }
return $results;
}
@@ -727,12 +756,15 @@ class Song extends database_object implements media, library_item
*/
public function get_album_name($album_id=0)
{
- if (!$album_id) { $album_id = $this->album; }
- $album = new Album($album_id);
- if ($album->prefix)
- return $album->prefix . " " . $album->name;
- else
- return $album->name;
+ if (!$album_id) {
+ $album_id = $this->album;
+ }
+ $album = new Album($album_id);
+ if ($album->prefix) {
+ return $album->prefix . " " . $album->name;
+ } else {
+ return $album->name;
+ }
} // get_album_name
/**
@@ -743,13 +775,15 @@ class Song extends database_object implements media, library_item
*/
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);
- if ($artist->prefix)
- return $artist->prefix . " " . $artist->name;
- else
- return $artist->name;
-
+ if ($artist->prefix) {
+ return $artist->prefix . " " . $artist->name;
+ } else {
+ return $artist->name;
+ }
} // get_artist_name
/**
@@ -760,13 +794,15 @@ class Song extends database_object implements media, library_item
*/
public function get_album_artist_name($album_artist_id=0)
{
- if (!$album_artist_id) { $album_artist_id = $this->albumartist; }
+ if (!$album_artist_id) {
+ $album_artist_id = $this->albumartist;
+ }
$album_artist = new Artist($album_artist_id);
- if ($album_artist->prefix)
- return $album_artist->prefix . " " . $album_artist->name;
- else
- return $album_artist->name;
-
+ if ($album_artist->prefix) {
+ return $album_artist->prefix . " " . $album_artist->name;
+ } else {
+ return $album_artist->name;
+ }
} // get_album_artist_name
/**
@@ -792,7 +828,6 @@ class Song extends database_object implements media, library_item
self::update_played(true, $this->id);
return true;
-
} // set_played
/**
@@ -809,41 +844,86 @@ class Song extends database_object implements media, library_item
{
// Remove some stuff we don't care about
unset($song->catalog,$song->played,$song->enabled,$song->addition_time,$song->update_time,$song->type);
+ $string_array = array('title','comment','lyrics','composer','tags');
+ $skip_array = array('id','tag_id','mime','artist_mbid','album_mbid','albumartist_mbid','albumartist','mbid','mb_albumid_group','waveform','object_cnt');
- $array = array();
- $string_array = array('title','comment','lyrics');
- $skip_array = array('id','tag_id','mime','artist_mbid','album_mbid','albumartist_mbid','albumartist','mbid','mb_albumid_group','waveform');
+ return self::compare_media_information($song, $new_song, $string_array, $skip_array);
+ } // compare_song_information
+
+ public static function compare_media_information($media, $new_media, $string_array, $skip_array)
+ {
+ $array = array();
// Pull out all the currently set vars
- $fields = get_object_vars($song);
+ $fields = get_object_vars($media);
// Foreach them
foreach ($fields as $key=>$value) {
- if (in_array($key,$skip_array)) { continue; }
+ $key = trim($key);
+ if (empty($key) || in_array($key,$skip_array)) {
+ continue;
+ }
+
+ // Represent the value as a string for simpler comparaison.
+ // For array, ensure to sort similarly old/new values
+ if (is_array($media->$key)) {
+ $arr = $media->$key;
+ sort($arr);
+ $mediaData = implode(" ", $arr);
+ } else {
+ $mediaData = $media->$key;
+ }
+
+ // Skip the item if it is no string nor something we can turn into a string
+ if (!is_string($mediaData) && !is_numeric($mediaData) && !is_bool($mediaData)) {
+ if (is_object($mediaData) && !method_exists($mediaData, '__toString')) {
+ continue;
+ }
+ }
+
+ if (is_array($new_media->$key)) {
+ $arr = $new_media->$key;
+ sort($arr);
+ $newMediaData = implode(" ", $arr);
+ } else {
+ $newMediaData = $new_media->$key;
+ }
+
// If it's a stringie thing
- if (in_array($key,$string_array)) {
- if (trim(stripslashes($song->$key)) != trim(stripslashes($new_song->$key))) {
- $array['change'] = true;
- $array['element'][$key] = 'OLD: ' . $song->$key . ' --> ' . $new_song->$key;
+ if (in_array($key, $string_array)) {
+ $mediaData = self::clean_string_field_value($mediaData);
+ $newMediaData = self::clean_string_field_value($newMediaData);
+ if ($mediaData != $newMediaData) {
+ $array['change'] = true;
+ $array['element'][$key] = 'OLD: ' . $mediaData . ' --> ' . $newMediaData;
}
} // in array of stringies
else {
- if ($song->$key != $new_song->$key) {
- $array['change'] = true;
- $array['element'][$key] = 'OLD:' . $song->$key . ' --> ' . $new_song->$key;
+ if ($media->$key != $new_media->$key) {
+ $array['change'] = true;
+ $array['element'][$key] = 'OLD:' . $mediaData . ' --> ' . $newMediaData;
}
} // end else
-
} // end foreach
if ($array['change']) {
- debug_event('song-diff', json_encode($array['element']), 5);
+ debug_event('media-diff', json_encode($array['element']), 5);
}
return $array;
+ }
- } // compare_song_information
+ private static function clean_string_field_value($value)
+ {
+ $value = trim(stripslashes(preg_replace('/\s+/', ' ', $value)));
+ // Strings containing only UTF-8 BOM = empty string
+ if (strlen($value) == 2 && (ord($value[0]) == 0xFF || ord($value[0]) == 0xFE)) {
+ $value = "";
+ }
+
+ return $value;
+ }
/**
* update
@@ -855,19 +935,19 @@ class Song extends database_object implements media, library_item
public function update(array $data)
{
foreach ($data as $key=>$value) {
- debug_event('song.class.php', $key.'='.$value, '5');
+ debug_event('song.class.php', $key . '=' . $value, '5');
switch ($key) {
case 'artist_name':
// Need to create new artist according the name
$new_artist_id = Artist::check($value);
- $this->artist = $new_artist_id;
+ $this->artist = $new_artist_id;
self::update_artist($new_artist_id, $this->id);
break;
case 'album_name':
// Need to create new album according the name
$new_album_id = Album::check($value);
- $this->album = $new_album_id;
+ $this->album = $new_album_id;
self::update_album($new_album_id, $this->id);
break;
case 'year':
@@ -892,6 +972,10 @@ class Song extends database_object implements media, library_item
Tag::update_tag_list($value, 'song', $this->id, true);
$this->tags = Tag::get_top_tags('song', $this->id);
break;
+ case 'metadata':
+ if (self::isCustomMetadataEnabled()) {
+ $this->updateMetadata($value);
+ }
default:
break;
} // end whitelist
@@ -913,8 +997,14 @@ class Song extends database_object implements media, library_item
if ($catalog->get_type() == 'local') {
debug_event('song', 'Writing id3 metadata to file ' . $this->file, 5);
$meta = $this->get_metadata();
+ if (self::isCustomMetadataEnabled()) {
+ foreach ($this->getMetadata() as $metadata) {
+ $meta[$metadata->getField()->getName()] = $metadata->getData();
+ }
+ }
$id3 = new vainfo($this->file);
$id3->write_id3($meta);
+ Catalog::update_media_from_tags($this);
}
}
}
@@ -959,7 +1049,6 @@ class Song extends database_object implements media, library_item
"WHERE `song_id` = ?";
Dba::write($sql, array($new_song->lyrics, $new_song->language, $new_song->comment, $new_song->replaygain_track_gain,
$new_song->replaygain_track_peak, $new_song->replaygain_album_gain, $new_song->replaygain_album_peak, $song_id));
-
} // update_song
/**
@@ -971,7 +1060,6 @@ class Song extends database_object implements media, library_item
public static function update_year($new_year, $song_id)
{
self::_update_item('year', $new_year, $song_id, 50, true);
-
} // update_year
/**
@@ -983,7 +1071,6 @@ class Song extends database_object implements media, library_item
public static function update_label($new_value, $song_id)
{
self::_update_ext_item('label', $new_value, $song_id, 50, true);
-
} // update_label
/**
@@ -995,7 +1082,6 @@ class Song extends database_object implements media, library_item
public static function update_language($new_lang, $song_id)
{
self::_update_ext_item('language', $new_lang, $song_id, 50, true);
-
} // update_language
/**
@@ -1007,7 +1093,6 @@ class Song extends database_object implements media, library_item
public static function update_comment($new_comment, $song_id)
{
self::_update_ext_item('comment', $new_comment, $song_id, 50, true);
-
} // update_comment
/**
@@ -1019,7 +1104,6 @@ class Song extends database_object implements media, library_item
public static function update_lyrics($new_lyrics, $song_id)
{
self::_update_ext_item('lyrics', $new_lyrics, $song_id, 50, true);
-
} // update_lyrics
/**
@@ -1031,7 +1115,6 @@ class Song extends database_object implements media, library_item
public static function update_title($new_title,$song_id)
{
self::_update_item('title', $new_title, $song_id, 50, true);
-
} // update_title
/**
@@ -1043,7 +1126,6 @@ class Song extends database_object implements media, library_item
public static function update_composer($new_value, $song_id)
{
self::_update_item('composer', $new_value, $song_id, 50, true);
-
} // update_composer
/**
@@ -1055,7 +1137,6 @@ class Song extends database_object implements media, library_item
public static function update_publisher($new_value, $song_id)
{
self::_update_item('publisher', $new_value, $song_id, 50, true);
-
} // update_publisher
/**
@@ -1067,7 +1148,6 @@ class Song extends database_object implements media, library_item
public static function update_bitrate($new_bitrate, $song_id)
{
self::_update_item('bitrate', $new_bitrate, $song_id, 50, true);
-
} // update_bitrate
/**
@@ -1079,7 +1159,6 @@ class Song extends database_object implements media, library_item
public static function update_rate($new_rate, $song_id)
{
self::_update_item('rate', $new_rate, $song_id, 50, true);
-
} // update_rate
/**
@@ -1091,7 +1170,6 @@ class Song extends database_object implements media, library_item
public static function update_mode($new_mode, $song_id)
{
self::_update_item('mode', $new_mode, $song_id, 50, true);
-
} // update_mode
/**
@@ -1103,7 +1181,6 @@ class Song extends database_object implements media, library_item
public static function update_size($new_size, $song_id)
{
self::_update_item('size', $new_size, $song_id, 50);
-
} // update_size
/**
@@ -1115,7 +1192,6 @@ class Song extends database_object implements media, library_item
public static function update_time($new_time, $song_id)
{
self::_update_item('time', $new_time, $song_id, 50, true);
-
} // update_time
/**
@@ -1127,7 +1203,6 @@ class Song extends database_object implements media, library_item
public static function update_track($new_track, $song_id)
{
self::_update_item('track', $new_track, $song_id, 50, true);
-
} // update_track
/**
@@ -1139,7 +1214,6 @@ class Song extends database_object implements media, library_item
public static function update_mbid($new_mbid, $song_id)
{
self::_update_item('mbid', $new_mbid, $song_id, 50);
-
} // update_mbid
/**
@@ -1151,7 +1225,6 @@ class Song extends database_object implements media, library_item
public static function update_license($new_license, $song_id)
{
self::_update_item('license', $new_license, $song_id, 50, true);
-
} // update_license
/**
@@ -1163,7 +1236,6 @@ class Song extends database_object implements media, library_item
public static function update_artist($new_artist, $song_id)
{
self::_update_item('artist', $new_artist, $song_id, 50);
-
} // update_artist
/**
@@ -1175,7 +1247,6 @@ class Song extends database_object implements media, library_item
public static function update_album($new_album, $song_id)
{
self::_update_item('album', $new_album, $song_id, 50, true);
-
} // update_album
/**
@@ -1186,10 +1257,11 @@ class Song extends database_object implements media, library_item
*/
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, true);
-
} // update_utime
/**
@@ -1201,7 +1273,6 @@ class Song extends database_object implements media, library_item
public static function update_played($new_played, $song_id)
{
self::_update_item('played', ($new_played ? 1 : 0), $song_id, 25);
-
} // update_played
/**
@@ -1213,7 +1284,6 @@ class Song extends database_object implements media, library_item
public static function update_enabled($new_enabled, $song_id)
{
self::_update_item('enabled', ($new_enabled ? 1 : 0), $song_id, 75, true);
-
} // update_enabled
/**
@@ -1238,14 +1308,17 @@ class Song extends database_object implements media, library_item
}
}
/* Check them Rights! */
- if (!Access::check('interface', $level)) { return false; }
+ if (!Access::check('interface', $level)) {
+ return false;
+ }
/* Can't update to blank */
- if (!strlen(trim($value)) && $field != 'comment') { return false; }
+ if (!strlen(trim($value)) && $field != 'comment') {
+ return false;
+ }
$sql = "UPDATE `song` SET `$field` = ? WHERE `id` = ?";
return Dba::write($sql, array($value, $song_id));
-
} // _update_item
/**
@@ -1269,11 +1342,12 @@ class Song extends database_object implements media, library_item
}
/* Check them rights boy! */
- if (!Access::check('interface',$level)) { return false; }
+ if (!Access::check('interface',$level)) {
+ return false;
+ }
$sql = "UPDATE `song_data` SET `$field` = ? WHERE `song_id` = ?";
return Dba::write($sql, array($value, $song_id));
-
} // _update_ext_item
/**
@@ -1288,29 +1362,29 @@ class Song extends database_object implements media, library_item
$this->fill_ext_info();
// Get the top tags
- $this->tags = Tag::get_top_tags('song', $this->id);
+ $this->tags = Tag::get_top_tags('song', $this->id);
$this->f_tags = Tag::get_display($this->tags, true, 'song');
}
// Format the album name
$this->f_album_full = $this->get_album_name();
- $this->f_album = $this->f_album_full;
+ $this->f_album = $this->f_album_full;
// Format the artist name
$this->f_artist_full = $this->get_artist_name();
- $this->f_artist = $this->f_artist_full;
+ $this->f_artist = $this->f_artist_full;
// Format the album_artist name
$this->f_albumartist_full = $this->get_album_artist_name();
// Format the title
$this->f_title_full = $this->title;
- $this->f_title = $this->title;
+ $this->f_title = $this->title;
// Create Links for the different objects
- $this->link = AmpConfig::get('web_path') . "/song.php?action=show_song&song_id=" . $this->id;
- $this->f_link = "link) . "\" title=\"" . scrub_out($this->f_artist) . " - " . scrub_out($this->title) . "\"> " . scrub_out($this->f_title) . "";
- $this->f_album_link = "album . "\" title=\"" . scrub_out($this->f_album_full) . "\"> " . scrub_out($this->f_album) . "";
+ $this->link = AmpConfig::get('web_path') . "/song.php?action=show_song&song_id=" . $this->id;
+ $this->f_link = "link) . "\" title=\"" . scrub_out($this->f_artist) . " - " . scrub_out($this->title) . "\"> " . scrub_out($this->f_title) . "";
+ $this->f_album_link = "album . "\" title=\"" . scrub_out($this->f_album_full) . "\"> " . scrub_out($this->f_album) . "";
$this->f_artist_link = "artist . "\" title=\"" . scrub_out($this->f_artist_full) . "\"> " . scrub_out($this->f_artist) . "";
if (!empty($this->albumartist)) {
$this->f_albumartist_link = "albumartist . "\" title=\"" . scrub_out($this->f_albumartist_full) . "\"> " . scrub_out($this->f_albumartist_full) . "";
@@ -1320,11 +1394,11 @@ class Song extends database_object implements media, library_item
$this->f_bitrate = intval($this->bitrate/1000) . "-" . strtoupper($this->mode);
// Format the Time
- $min = floor($this->time/60);
- $sec = sprintf("%02d", ($this->time%60));
- $this->f_time = $min . ":" . $sec;
- $hour = sprintf("%02d", floor($min/60));
- $min_h = sprintf("%02d", ($min%60));
+ $min = floor($this->time/60);
+ $sec = sprintf("%02d", ($this->time%60));
+ $this->f_time = $min . ":" . $sec;
+ $hour = sprintf("%02d", floor($min/60));
+ $min_h = sprintf("%02d", ($min%60));
$this->f_time_h = $hour . ":" . $min_h . ":" . $sec;
// Format the track (there isn't really anything to do here)
@@ -1342,8 +1416,7 @@ class Song extends database_object implements media, library_item
$this->f_file .= $this->f_title . '.' . $this->type;
$this->f_publisher = $this->label;
- $this->f_composer = $this->composer;
-
+ $this->f_composer = $this->composer;
} // format
/**
@@ -1352,7 +1425,7 @@ class Song extends database_object implements media, library_item
*/
public function get_keywords()
{
- $keywords = array();
+ $keywords = array();
$keywords['mb_trackid'] = array('important' => false,
'label' => T_('Track MusicBrainzID'),
'value' => $this->mbid);
@@ -1455,8 +1528,9 @@ class Song extends database_object implements media, library_item
public function get_description()
{
- if (!empty($this->comment))
+ if (!empty($this->comment)) {
return $this->comment;
+ }
$album = new Album($this->album);
$album->format();
@@ -1465,18 +1539,22 @@ class Song extends database_object implements media, library_item
public function display_art($thumb = 2)
{
- $id = null;
+ $id = null;
$type = null;
if (Art::has_db($this->id, 'song')) {
- $id = $this->id;
+ $id = $this->id;
$type = 'song';
- } else if (Art::has_db($this->album, 'album')) {
- $id = $this->album;
- $type = 'album';
- } else if (Art::has_db($this->artist, 'artist')) {
- $id = $this->artist;
- $type = 'artist';
+ } else {
+ if (Art::has_db($this->album, 'album')) {
+ $id = $this->album;
+ $type = 'album';
+ } else {
+ if (Art::has_db($this->artist, 'artist')) {
+ $id = $this->artist;
+ $type = 'artist';
+ }
+ }
}
if ($id !== null && $type !== null) {
@@ -1497,14 +1575,13 @@ class Song extends database_object implements media, library_item
unset($fields['id'],$fields['_transcoded'],$fields['_fake'],$fields['cache_hit'],$fields['mime'],$fields['type']);
// Some additional fields
- $fields['tag'] = true;
+ $fields['tag'] = true;
$fields['catalog'] = true;
//FIXME: These are here to keep the ideas, don't want to have to worry about them for now
// $fields['rating'] = true;
// $fields['recently Played'] = true;
return $fields;
-
} // get_fields
/**
@@ -1517,7 +1594,7 @@ class Song extends database_object implements media, library_item
{
$path = Dba::escape($path);
- $sql = "SELECT * FROM `song` WHERE `file` LIKE '$path%'";
+ $sql = "SELECT * FROM `song` WHERE `file` LIKE '$path%'";
$db_results = Dba::read($sql);
$songs = array();
@@ -1527,7 +1604,6 @@ class Song extends database_object implements media, library_item
}
return $songs;
-
} // get_from_path
/**
@@ -1542,7 +1618,7 @@ class Song extends database_object implements media, library_item
{
$info = null;
if (!$file_path) {
- $info = $this->_get_info();
+ $info = $this->_get_info();
$file_path = $info['file'];
}
if (!$catalog_id) {
@@ -1553,7 +1629,6 @@ class Song extends database_object implements media, library_item
}
$catalog = Catalog::create_from_id( $catalog_id );
return $catalog->get_rel_path($file_path);
-
} // get_rel_path
/**
@@ -1567,27 +1642,28 @@ class Song extends database_object implements media, library_item
public static function generic_play_url($object_type, $object_id, $additional_params, $player=null, $local=false)
{
$media = new $object_type($object_id);
- if (!$media->id) return null;
+ if (!$media->id) {
+ return null;
+ }
- $uid = $GLOBALS['user']->id ? scrub_out($GLOBALS['user']->id) : '-1';
+ $uid = $GLOBALS['user']->id ? scrub_out($GLOBALS['user']->id) : '-1';
$type = $media->type;
// Checking if the media is gonna be transcoded into another type
// Some players doesn't allow a type streamed into another without giving the right extension
$transcode_cfg = AmpConfig::get('transcode');
- $valid_types = Song::get_stream_types_for_type($type, $player);
+ $valid_types = Song::get_stream_types_for_type($type, $player);
if ($transcode_cfg == 'always' || ($transcode_cfg != 'never' && !in_array('native', $valid_types))) {
$transcode_settings = $media->get_transcode_settings(null);
if ($transcode_settings) {
- debug_event("media", "Changing play url type from {".$type."} to {".$transcode_settings['format']."} due to encoding settings...", 5);
+ debug_event("media", "Changing play url type from {" . $type . "} to {" . $transcode_settings['format'] . "} due to encoding settings...", 5);
$type = $transcode_settings['format'];
}
}
+ $media->format();
$media_name = $media->get_stream_name() . "." . $type;
- $media_name = str_replace("/", "-", $media_name);
- $media_name = str_replace("?", "", $media_name);
- $media_name = str_replace("#", "", $media_name);
+ $media_name = preg_replace("/[^a-zA-Z0-9\. ]+/", "-", $media_name);
$media_name = rawurlencode($media_name);
$url = Stream::get_base_url($local) . "type=" . $object_type . "&oid=" . $object_id . "&uid=" . $uid . $additional_params;
@@ -1643,15 +1719,18 @@ class Song extends database_object implements media, library_item
if ($user_id) {
// If user is not empty, we're looking directly to user personal info (admin view)
$sql .= "AND `user`='$user_id' ";
- } else if (!Access::check('interface','100')) {
- // If user identifier is empty, we need to retrieve only users which have allowed view of personnal info
+ } else {
+ if (!Access::check('interface','100')) {
+ // If user identifier is empty, we need to retrieve only users which have allowed view of personnal info
$personal_info_id = Preference::id_from_name('allow_personal_info_recent');
- if ($personal_info_id) {
- $current_user = $GLOBALS['user']->id;
- $sql .= "AND `user` IN (SELECT `user` FROM `user_preference` WHERE (`preference`='$personal_info_id' AND `value`='1') OR `user`='$current_user') ";
+ if ($personal_info_id) {
+ $current_user = $GLOBALS['user']->id;
+ $sql .= "AND `user` IN (SELECT `user` FROM `user_preference` WHERE (`preference`='$personal_info_id' AND `value`='1') OR `user`='$current_user') ";
+ }
}
}
$sql .= "ORDER BY `date` DESC ";
+ $sql .= "LIMIT " . intval(AmpConfig::get('popular_threshold')) . " ";
$db_results = Dba::read($sql);
$results = array();
@@ -1661,11 +1740,9 @@ class Song extends database_object implements media, library_item
$row['geo_name'] = Stats::get_cached_place_name($row['latitude'], $row['longitude']);
}
$results[] = $row;
- if (count($results) >= AmpConfig::get('popular_threshold')) { break; }
}
return $results;
-
} // get_recently_played
/**
@@ -1684,7 +1761,7 @@ class Song extends database_object implements media, library_item
*/
public static function get_stream_types_for_type($type, $player = null)
{
- $types = array();
+ $types = array();
$transcode = AmpConfig::get('transcode_' . $type);
if ($player) {
$player_transcode = AmpConfig::get('transcode_player_' . $player . '_' . $type);
@@ -1730,18 +1807,22 @@ class Song extends database_object implements media, library_item
if ($target) {
debug_event('media', 'Explicit format request {' . $target . '}', 5);
- } else if ($target = AmpConfig::get('encode_target_' . $source)) {
- debug_event('media', 'Defaulting to configured target format for ' . $source, 5);
- } else if ($target = AmpConfig::get($setting_target)) {
- debug_event('media', 'Using default target format', 5);
} else {
- $target = $source;
- debug_event('media', 'No default target for ' . $source . ', choosing to resample', 5);
+ if ($target = AmpConfig::get('encode_target_' . $source)) {
+ debug_event('media', 'Defaulting to configured target format for ' . $source, 5);
+ } else {
+ if ($target = AmpConfig::get($setting_target)) {
+ debug_event('media', 'Using default target format', 5);
+ } else {
+ $target = $source;
+ debug_event('media', 'No default target for ' . $source . ', choosing to resample', 5);
+ }
+ }
}
debug_event('media', 'Transcode settings: from ' . $source . ' to ' . $target, 5);
- $cmd = AmpConfig::get('transcode_cmd_' . $source) ?: AmpConfig::get('transcode_cmd');
+ $cmd = AmpConfig::get('transcode_cmd_' . $source) ?: AmpConfig::get('transcode_cmd');
$args = '';
if (AmpConfig::get('encode_ss_frame') && isset($options['frame'])) {
$args .= ' ' . AmpConfig::get('encode_ss_frame');
@@ -1811,7 +1892,7 @@ class Song extends database_object implements media, library_item
public function run_custom_play_action($action_index, $codec='')
{
$transcoder = array();
- $actions = Song::get_custom_play_actions();
+ $actions = Song::get_custom_play_actions();
if ($action_index <= count($actions)) {
$action = $actions[$action_index - 1];
if (!$codec) {
@@ -1834,9 +1915,9 @@ class Song extends database_object implements media, library_item
$process = proc_open($run, $descriptors, $pipes);
$transcoder['process'] = $process;
- $transcoder['handle'] = $pipes[1];
- $transcoder['stderr'] = $pipes[2];
- $transcoder['format'] = $codec;
+ $transcoder['handle'] = $pipes[1];
+ $transcoder['stderr'] = $pipes[2];
+ $transcoder['format'] = $codec;
}
return $transcoder;
@@ -1860,7 +1941,7 @@ class Song extends database_object implements media, library_item
public static function get_custom_play_actions()
{
$actions = array();
- $i = 0;
+ $i = 0;
while (AmpConfig::get('custom_play_action_title_' . $i)) {
$actions[] = array(
'index' => ($i + 1),
@@ -1883,28 +1964,28 @@ class Song extends database_object implements media, library_item
{
$meta = array();
- $meta['file'] = $this->file;
- $meta['bitrate'] = $this->bitrate;
- $meta['rate'] = $this->rate;
- $meta['mode'] = $this->mode;
- $meta['year'] = $this->year;
- $meta['size'] = $this->size;
- $meta['time'] = $this->time;
- $meta['mime'] = $this->mime;
- $meta['title'] = $this->title;
- $meta['album'] = $this->f_album_full;
- $meta['artist'] = $this->f_artist_full;
- $meta['band'] = $meta['albumartist'] = $this->f_albumartist_full;
- $meta['mb_trackid'] = $this->mbid;
- $meta['mb_albumid'] = $this->album_mbid;
- $meta['mb_artistid'] = $this->artist_mbid;
- $meta['mb_albumartistid'] = $this->albumartist_mbid;
- $meta['tracknumber'] = $meta['track'] = $this->track;
+ $meta['file'] = $this->file;
+ $meta['bitrate'] = $this->bitrate;
+ $meta['rate'] = $this->rate;
+ $meta['mode'] = $this->mode;
+ $meta['year'] = $this->year;
+ $meta['size'] = $this->size;
+ $meta['time'] = $this->time;
+ $meta['mime'] = $this->mime;
+ $meta['title'] = $this->title;
+ $meta['album'] = $this->f_album_full;
+ $meta['artist'] = $this->f_artist_full;
+ $meta['band'] = $meta['albumartist'] = $this->f_albumartist_full;
+ $meta['mb_trackid'] = $this->mbid;
+ $meta['mb_albumid'] = $this->album_mbid;
+ $meta['mb_artistid'] = $this->artist_mbid;
+ $meta['mb_albumartistid'] = $this->albumartist_mbid;
+ $meta['tracknumber'] = $meta['track'] = $this->track;
$meta['replaygain_track_gain'] = $this->replaygain_track_gain;
$meta['replaygain_track_peak'] = $this->replaygain_track_peak;
$meta['replaygain_album_gain'] = $this->replaygain_album_gain;
$meta['replaygain_album_peak'] = $this->replaygain_album_peak;
- $meta['genre'] = array();
+ $meta['genre'] = array();
if ($this->tags) {
foreach ($this->tags as $tag) {
if (!in_array($tag['name'], $meta['genre'])) {
@@ -1917,6 +1998,26 @@ class Song extends database_object implements media, library_item
return $meta;
}
+ public function getId()
+ {
+ return $this->id;
+ }
+
+ /**
+ * Update Metadata from array
+ * @param array $value
+ */
+ public function updateMetadata($value)
+ {
+ foreach ($value as $metadataId => $value) {
+ $metadata = $this->metadataRepository->findById($metadataId);
+ if (!$metadata || $value != $metadata->getData()) {
+ $metadata->setData($value);
+ $this->metadataRepository->update($metadata);
+ }
+ }
+ }
+
/**
* Remove the song from disk.
*/
@@ -1928,13 +2029,14 @@ class Song extends database_object implements media, library_item
$deleted = true;
}
if ($deleted === true) {
- $sql = "DELETE FROM `song` WHERE `id` = ?";
+ $sql = "DELETE FROM `song` WHERE `id` = ?";
$deleted = Dba::write($sql, array($this->id));
if ($deleted) {
Art::gc('song', $this->id);
Userflag::gc('song', $this->id);
Rating::gc('song', $this->id);
Shoutbox::gc('song', $this->id);
+ Useractivity::gc('song', $this->id);
}
} else {
debug_event('song', 'Cannot delete ' . $this->file . 'file. Please check permissions.', 1);
@@ -1942,5 +2044,5 @@ class Song extends database_object implements media, library_item
return $deleted;
}
-
} // end of song class
+
diff --git a/sources/lib/class/song_preview.class.php b/sources/lib/class/song_preview.class.php
index a83988b..cd96607 100644
--- a/sources/lib/class/song_preview.class.php
+++ b/sources/lib/class/song_preview.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -54,7 +54,9 @@ class Song_Preview extends database_object implements media, playable_item
*/
public function __construct($id = null)
{
- if (!$id) { return false; }
+ if (!$id) {
+ return false;
+ }
$this->id = intval($id);
@@ -62,7 +64,7 @@ class Song_Preview extends database_object implements media, playable_item
foreach ($info as $key => $value) {
$this->$key = $value;
}
- $data = pathinfo($this->file);
+ $data = pathinfo($this->file);
$this->type = strtolower($data['extension']) ?: 'mp3';
$this->mime = Song::type_to_mime($this->type);
} else {
@@ -71,7 +73,6 @@ class Song_Preview extends database_object implements media, playable_item
}
return true;
-
} // constructor
/**
@@ -113,12 +114,16 @@ class Song_Preview extends database_object implements media, playable_item
*/
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) . ')';
// Callers might have passed array(false) because they are dumb
- if ($idlist == '()') { return false; }
+ if ($idlist == '()') {
+ return false;
+ }
// Song data cache
$sql = 'SELECT `id`, `file`, `album_mbid`, `artist`, `artist_mbid`, `title`, `disk`, `track`, `mbid` ' .
@@ -137,7 +142,6 @@ class Song_Preview extends database_object implements media, playable_item
Artist::build_cache($artists);
return true;
-
} // build_cache
/**
@@ -158,7 +162,7 @@ class Song_Preview extends database_object implements media, playable_item
$results = Dba::fetch_assoc($db_results);
if (!empty($results['id'])) {
if (empty($results['artist_mbid'])) {
- $sql = 'SELECT `mbid` FROM `artist` WHERE `id` = ?';
+ $sql = 'SELECT `mbid` FROM `artist` WHERE `id` = ?';
$db_results = Dba::read($sql, array($results['artist']));
if ($artist_res = Dba::fetch_assoc($db_results)) {
$results['artist_mbid'] = $artist_res['mbid'];
@@ -177,13 +181,15 @@ class Song_Preview extends database_object implements media, playable_item
*/
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);
- if ($artist->prefix)
- return $artist->prefix . " " . $artist->name;
- else
- return $artist->name;
-
+ if ($artist->prefix) {
+ return $artist->prefix . " " . $artist->name;
+ } else {
+ return $artist->name;
+ }
} // get_album_name
/**
@@ -199,7 +205,7 @@ class Song_Preview extends database_object implements media, playable_item
$this->f_artist_full = $this->get_artist_name();
$this->f_artist_link = "artist . "\" title=\"" . scrub_out($this->f_artist_full) . "\"> " . scrub_out($this->f_artist) . "";
} else {
- $wartist = Wanted::get_missing_artist($this->artist_mbid);
+ $wartist = Wanted::get_missing_artist($this->artist_mbid);
$this->f_artist_link = $wartist['link'];
$this->f_artist_full = $wartist['name'];
}
@@ -207,17 +213,16 @@ class Song_Preview extends database_object implements media, playable_item
// Format the title
$this->f_title_full = $this->title;
- $this->f_title = $this->title;
+ $this->f_title = $this->title;
- $this->link = "#";
- $this->f_link = "link) . "\" title=\"" . scrub_out($this->f_artist) . " - " . scrub_out($this->title) . "\"> " . scrub_out($this->f_title) . "";
+ $this->link = "#";
+ $this->f_link = "link) . "\" title=\"" . scrub_out($this->f_artist) . " - " . scrub_out($this->title) . "\"> " . scrub_out($this->f_title) . "";
$this->f_album_link = "album_mbid . "&artist=" . $this->artist . "\" title=\"" . $this->f_album . "\">" . $this->f_album . "";
// Format the track (there isn't really anything to do here)
$this->f_track = $this->track;
return true;
-
} // format
public function get_fullname()
@@ -272,7 +277,7 @@ class Song_Preview extends database_object implements media, playable_item
*/
public static function play_url($oid, $additional_params='', $player=null, $local=false)
{
- $song = new Song_Preview($oid);
+ $song = new Song_Preview($oid);
$user_id = $GLOBALS['user']->id ? scrub_out($GLOBALS['user']->id) : '-1';
$type = $song->type;
@@ -281,7 +286,6 @@ class Song_Preview extends database_object implements media, playable_item
$url = Stream::get_base_url($local) . "type=song_preview&oid=" . $song->id . "&uid=" . $user_id . "&name=" . $song_name;
return Stream_URL::format($url . $additional_params);
-
} // play_url
public function stream()
@@ -290,8 +294,9 @@ class Song_Preview extends database_object implements media, playable_item
foreach (Plugin::get_plugins('stream_song_preview') as $plugin_name) {
$plugin = new Plugin($plugin_name);
if ($plugin->load($GLOBALS['user'])) {
- if ($plugin->_plugin->stream_song_preview($this->file))
+ if ($plugin->_plugin->stream_song_preview($this->file)) {
break;
+ }
}
}
@@ -345,5 +350,5 @@ class Song_Preview extends database_object implements media, playable_item
'WHERE `session`.`id` IS NULL';
return Dba::write($sql);
}
-
} // end of song_preview class
+
diff --git a/sources/lib/class/stats.class.php b/sources/lib/class/stats.class.php
index 9848d9b..6eea8ec 100644
--- a/sources/lib/class/stats.class.php
+++ b/sources/lib/class/stats.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -46,7 +46,6 @@ class Stats
public function __construct()
{
return true;
-
} // Constructor
/**
@@ -100,19 +99,26 @@ class Stats
if (!self::is_already_inserted($type, $oid, $user)) {
$type = self::validate_type($type);
- $latitude = null;
+ $latitude = null;
$longitude = null;
- $geoname = null;
- if (isset($location['latitude']))
+ $geoname = null;
+ if (isset($location['latitude'])) {
$latitude = $location['latitude'];
- if (isset($location['longitude']))
+ }
+ if (isset($location['longitude'])) {
$longitude = $location['longitude'];
- if (isset($location['name']))
+ }
+ if (isset($location['name'])) {
$geoname = $location['name'];
+ }
$sql = "INSERT INTO `object_count` (`object_type`,`object_id`,`count_type`,`date`,`user`,`agent`, `geo_latitude`, `geo_longitude`, `geo_name`) " .
" VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
$db_results = Dba::write($sql, array($type, $oid, $count_type, time(), $user, $agent, $latitude, $longitude, $geoname));
+
+ if (Core::is_media($type)) {
+ Useractivity::post_activity($user, 'play', $type, $oid);
+ }
if (!$db_results) {
debug_event('statistics', 'Unabled to insert statistics:' . $sql, '3');
@@ -135,14 +141,13 @@ class Stats
$sql .= "ORDER BY `object_count`.`date` DESC";
$db_results = Dba::read($sql, array($user, $type, $oid, $count_type, $delay));
- $results = array();
+ $results = array();
while ($row = Dba::fetch_assoc($db_results)) {
$results[] = $row['id'];
}
return count($results) > 0;
-
} // is_already_inserted
/**
@@ -170,8 +175,8 @@ class Stats
public static function get_cached_place_name($latitude, $longitude)
{
- $name = null;
- $sql = "SELECT `geo_name` FROM `object_count` WHERE `geo_latitude` = ? AND `geo_longitude` = ? AND `geo_name` IS NOT NULL ORDER BY `id` DESC LIMIT 1";
+ $name = null;
+ $sql = "SELECT `geo_name` FROM `object_count` WHERE `geo_latitude` = ? AND `geo_longitude` = ? AND `geo_name` IS NOT NULL ORDER BY `id` DESC LIMIT 1";
$db_results = Dba::read($sql, array($latitude, $longitude));
if ($results = Dba::fetch_assoc($db_results)) {
$name = $results['geo_name'];
@@ -205,7 +210,6 @@ class Stats
$results = Dba::fetch_assoc($db_results);
return $results;
-
} // get_last_song
/**
@@ -236,7 +240,6 @@ class Stats
}
return $results;
-
} // get_object_history
/**
@@ -254,7 +257,7 @@ class Stats
/* Select Top objects counting by # of rows */
$sql = "SELECT object_id as `id`, COUNT(*) AS `count` FROM object_count" .
- " WHERE `object_type` = '" . $type ."' AND `date` >= '" . $date . "' ";
+ " WHERE `object_type` = '" . $type . "' AND `date` >= '" . $date . "' ";
if (AmpConfig::get('catalog_disable')) {
$sql .= "AND " . Catalog::get_enable_filter($type, '`object_id`');
}
@@ -291,7 +294,6 @@ class Stats
$results[] = $row['id'];
}
return $results;
-
} // get_top
/**
@@ -308,7 +310,7 @@ class Stats
}
$sql = "SELECT DISTINCT(`object_id`) as `id`, MAX(`date`) FROM object_count" .
- " WHERE `object_type` = '" . $type ."'" . $user_sql;
+ " WHERE `object_type` = '" . $type . "'" . $user_sql;
if (AmpConfig::get('catalog_disable')) {
$sql .= " AND " . Catalog::get_enable_filter($type, '`object_id`');
}
@@ -328,7 +330,7 @@ class Stats
}
$count = intval($count);
- $type = self::validate_type($type);
+ $type = self::validate_type($type);
if (!$offset) {
$limit = $count;
} else {
@@ -345,7 +347,6 @@ class Stats
}
return $results;
-
} // get_recent
/**
@@ -356,7 +357,7 @@ class Stats
public static function get_user($count,$type,$user,$full='')
{
$count = intval($count);
- $type = self::validate_type($type);
+ $type = self::validate_type($type);
/* If full then don't limit on date */
if ($full) {
@@ -379,7 +380,6 @@ class Stats
}
return $results;
-
} // get_user
/**
@@ -404,7 +404,6 @@ class Stats
default:
return 'song';
} // end switch
-
} // validate_type
/**
@@ -418,16 +417,16 @@ class Stats
$base_type = 'song';
if ($type == 'video') {
$base_type = $type;
- $type = $type . '`.`id';
+ $type = $type . '`.`id';
}
$sql = "SELECT DISTINCT(`$type`) as `id`, MIN(`addition_time`) AS `real_atime` FROM `" . $base_type . "` ";
$sql .= "LEFT JOIN `catalog` ON `catalog`.`id` = `" . $base_type . "`.`catalog` ";
if (AmpConfig::get('catalog_disable')) {
- $sql .= "WHERE `catalog`.`enabled` = '1' ";
+ $sql .= "WHERE `catalog`.`enabled` = '1' ";
}
if ($catalog > 0) {
- $sql .= "AND `catalog` = '" . scrub_in($catalog) ."' ";
+ $sql .= "AND `catalog` = '" . scrub_in($catalog) . "' ";
}
$sql .= "GROUP BY `$type` ORDER BY `real_atime` DESC ";
@@ -441,7 +440,9 @@ class Stats
*/
public static function get_newest($type, $count='', $offset='', $catalog=0)
{
- if (!$count) { $count = AmpConfig::get('popular_threshold'); }
+ if (!$count) {
+ $count = AmpConfig::get('popular_threshold');
+ }
if (!$offset) {
$limit = $count;
} else {
@@ -459,7 +460,6 @@ class Stats
} // end while results
return $items;
-
} // get_newest
-
} // Stats class
+
diff --git a/sources/lib/class/stream.class.php b/sources/lib/class/stream.class.php
index 3b72577..b000e1c 100644
--- a/sources/lib/class/stream.class.php
+++ b/sources/lib/class/stream.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -45,7 +45,7 @@ class Stream
{
if (!self::$session) {
// Generate the session ID. This is slightly wasteful.
- $data = array();
+ $data = array();
$data['type'] = 'stream';
// This shouldn't be done here but at backend endpoint side
if (isset($_REQUEST['client'])) {
@@ -82,11 +82,11 @@ class Stream
$max_bitrate = AmpConfig::get('max_bit_rate');
$min_bitrate = AmpConfig::get('min_bit_rate');
// FIXME: This should be configurable for each output type
- $user_sample_rate = AmpConfig::get('sample_rate');
+ $user_bit_rate = AmpConfig::get('transcode_bitrate');
// If the user's crazy, that's no skin off our back
- if ($user_sample_rate < $min_bitrate) {
- $min_bitrate = $user_sample_rate;
+ if ($user_bit_rate < $min_bitrate) {
+ $min_bitrate = $user_bit_rate;
}
// Are there site-wide constraints? (Dynamic downsampling.)
@@ -101,7 +101,7 @@ class Stream
"AND `user_preference`.`value` = 'downsample')";
$db_results = Dba::read($sql);
- $results = Dba::fetch_row($db_results);
+ $results = Dba::fetch_row($db_results);
$active_streams = intval($results[0]) ?: 0;
debug_event('stream', 'Active transcoding streams: ' . $active_streams, 5);
@@ -109,25 +109,25 @@ class Stream
// We count as one for the algorithm
// FIXME: Should this reflect the actual bit rates?
$active_streams++;
- $sample_rate = floor($max_bitrate / $active_streams);
+ $bit_rate = floor($max_bitrate / $active_streams);
// Exit if this would be insane
- if ($sample_rate < ($min_bitrate ?: 8)) {
+ if ($bit_rate < ($min_bitrate ?: 8)) {
debug_event('stream', 'Max transcode bandwidth already allocated. Active streams: ' . $active_streams, 2);
header('HTTP/1.1 503 Service Temporarily Unavailable');
exit();
}
// Never go over the user's sample rate
- if ($sample_rate > $user_sample_rate) {
- $sample_rate = $user_sample_rate;
+ if ($bit_rate > $user_bit_rate) {
+ $bit_rate = $user_bit_rate;
}
} // end if we've got bitrates
else {
- $sample_rate = $user_sample_rate;
+ $bit_rate = $user_bit_rate;
}
- return $sample_rate;
+ return $bit_rate;
}
/**
@@ -138,32 +138,32 @@ class Stream
*/
public static function start_transcode($media, $type = null, $player = null, $options = array())
{
- debug_event('stream.class.php', 'Starting transcode for {'.$media->file.'}. Type {'.$type.'}. Options: ' . print_r($options, true) . '}...', 5);
+ debug_event('stream.class.php', 'Starting transcode for {' . $media->file . '}. Type {' . $type . '}. Options: ' . print_r($options, true) . '}...', 5);
$transcode_settings = $media->get_transcode_settings($type, $player, $options);
// Bail out early if we're unutterably broken
- if ($transcode_settings == false) {
+ if ($transcode_settings === false) {
debug_event('stream', 'Transcode requested, but get_transcode_settings failed', 2);
return false;
}
//$media_rate = $media->video_bitrate ?: $media->bitrate;
if (!$options['bitrate']) {
- $sample_rate = self::get_allowed_bitrate($media);
- debug_event('stream', 'Configured bitrate is ' . $sample_rate, 5);
+ $bit_rate = self::get_allowed_bitrate($media);
+ debug_event('stream', 'Configured bitrate is ' . $bit_rate, 5);
// Validate the bitrate
- $sample_rate = self::validate_bitrate($sample_rate);
+ $bit_rate = self::validate_bitrate($bit_rate);
} else {
- $sample_rate = $options['bitrate'];
+ $bit_rate = $options['bitrate'];
}
// Never upsample a media
- if ($media->type == $transcode_settings['format'] && ($sample_rate * 1000) > $media->bitrate) {
- debug_event('stream', 'Clamping bitrate to avoid upsampling to ' . $sample_rate, 5);
- $sample_rate = self::validate_bitrate($media->bitrate / 1000);
+ if ($media->type == $transcode_settings['format'] && ($bit_rate * 1000) > $media->bitrate) {
+ debug_event('stream', 'Clamping bitrate to avoid upsampling to ' . $bit_rate, 5);
+ $bit_rate = self::validate_bitrate($media->bitrate / 1000);
}
- debug_event('stream', 'Final transcode bitrate is ' . $sample_rate, 5);
+ debug_event('stream', 'Final transcode bitrate is ' . $bit_rate, 5);
$song_file = scrub_arg($media->file);
@@ -172,7 +172,8 @@ class Stream
$string_map = array(
'%FILE%' => $song_file,
- '%SAMPLE%' => $sample_rate
+ '%SAMPLE%' => $bit_rate, // Deprecated
+ '%BITRATE%' => $bit_rate
);
if (isset($options['maxbitrate'])) {
$string_map['%MAXBITRATE%'] = $options['maxbitrate'];
@@ -180,11 +181,11 @@ class Stream
$string_map['%MAXBITRATE%'] = 8000;
}
if (isset($options['frame'])) {
- $frame = gmdate("H:i:s", $options['frame']);
+ $frame = gmdate("H:i:s", $options['frame']);
$string_map['%TIME%'] = $frame;
}
if (isset($options['duration'])) {
- $duration = gmdate("H:i:s", $options['duration']);
+ $duration = gmdate("H:i:s", $options['duration']);
$string_map['%DURATION%'] = $duration;
}
if (isset($options['resolution'])) {
@@ -215,12 +216,11 @@ class Stream
public static function get_image_preview($media)
{
$image = null;
- $sec = ($media->time >= 30) ? 30 : intval($media->time / 2);
+ $sec = ($media->time >= 30) ? 30 : intval($media->time / 2);
$frame = gmdate("H:i:s", $sec);
if (AmpConfig::get('transcode_cmd') && AmpConfig::get('transcode_input') && AmpConfig::get('encode_get_image')) {
-
- $command = AmpConfig::get('transcode_cmd') . ' ' . AmpConfig::get('transcode_input') . ' ' . AmpConfig::get('encode_get_image');
+ $command = AmpConfig::get('transcode_cmd') . ' ' . AmpConfig::get('transcode_input') . ' ' . AmpConfig::get('encode_get_image');
$string_map = array(
'%FILE%' => scrub_arg($media->file),
'%TIME%' => $frame
@@ -255,22 +255,31 @@ class Stream
if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
// Windows doesn't like to provide stderr as a pipe
$descriptors[2] = array('pipe', 'w');
- $cmdPrefix = "exec ";
- } else
+ $cmdPrefix = "exec ";
+ } else {
$cmdPrefix = "start /B ";
+ }
debug_event('stream', "Transcode command prefix: " . $cmdPrefix, 3);
- $process = proc_open($cmdPrefix.$command, $descriptors, $pipes);
- $parray = array(
- 'process' => $process,
- 'handle' => $pipes[1],
- 'stderr' => $pipes[2]
- );
+ $parray = array();
+ $process = proc_open($cmdPrefix . $command, $descriptors, $pipes);
+ if ($process === false) {
+ debug_event('stream', 'Transcode command failed to open.', 1);
+ $parray = array(
+ 'handle' => null
+ );
+ } else {
+ $parray = array(
+ 'process' => $process,
+ 'handle' => $pipes[1],
+ 'stderr' => $pipes[2]
+ );
- if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
- stream_set_blocking($pipes[2], 0); // Be sure stderr is non-blocking
+ if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
+ stream_set_blocking($pipes[2], 0); // Be sure stderr is non-blocking
+ }
}
return array_merge($parray, $settings);
@@ -283,7 +292,7 @@ class Stream
$pid = $status['pid'];
debug_event('stream', 'Stream process about to be killed. pid:' . $pid, 1);
- (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') ? exec("taskkill /F /T /PID $pid") : exec("kill -9 $pid");
+ (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') ? exec("kill -9 $pid") : exec("taskkill /F /T /PID $pid");
proc_close($transcoder['process']);
} else {
@@ -298,9 +307,9 @@ class Stream
public static function validate_bitrate($bitrate)
{
/* Round to standard bitrates */
- $sample_rate = 16*(floor($bitrate/16));
+ $bit_rate = 16*(floor($bitrate/16));
- return $sample_rate;
+ return $bit_rate;
}
/**
@@ -361,7 +370,7 @@ class Stream
if (AmpConfig::get('now_playing_per_user')) {
$sql .= 'INNER JOIN ( ' .
- 'SELECT MAX(`insertion`) AS `max_insertion`, `user`, `id` ' .
+ 'SELECT MAX(`insertion`) AS `max_insertion`, `user` ' .
'FROM `now_playing` ' .
'GROUP BY `user`' .
') `np2` ' .
@@ -384,7 +393,7 @@ class Stream
$results = array();
while ($row = Dba::fetch_assoc($db_results)) {
- $type = $row['object_type'];
+ $type = $row['object_type'];
$media = new $type($row['object_id']);
$media->format();
$client = new User($row['user']);
@@ -398,7 +407,6 @@ class Stream
} // end while
return $results;
-
} // get_now_playing
/**
@@ -431,7 +439,9 @@ class Stream
public static function run_playlist_method()
{
// If this wasn't ajax included run away
- if (!defined('AJAX_INCLUDE')) { return false; }
+ if (!defined('AJAX_INCLUDE')) {
+ return false;
+ }
switch (AmpConfig::get('playlist_method')) {
case 'send':
@@ -449,9 +459,8 @@ class Stream
// Load our javascript
echo "";
-
} // run_playlist_method
/**
@@ -487,7 +496,6 @@ class Stream
$url = $web_path . "/play/index.php?$session_string";
return $url;
-
} // get_base_url
-
} //end of stream class
+
diff --git a/sources/lib/class/stream_playlist.class.php b/sources/lib/class/stream_playlist.class.php
index ae84e04..05a295f 100644
--- a/sources/lib/class/stream_playlist.class.php
+++ b/sources/lib/class/stream_playlist.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -33,6 +33,8 @@ class Stream_Playlist
public $id;
public $urls = array();
public $user;
+
+ public $title;
/**
* Stream_Playlist constructor
@@ -54,7 +56,7 @@ class Stream_Playlist
$this->user = intval($GLOBALS['user']->id);
- $sql = 'SELECT * FROM `stream_playlist` WHERE `sid` = ? ORDER BY `id`';
+ $sql = 'SELECT * FROM `stream_playlist` WHERE `sid` = ? ORDER BY `id`';
$db_results = Dba::read($sql, array($this->id));
while ($row = Dba::fetch_assoc($db_results)) {
@@ -67,23 +69,23 @@ class Stream_Playlist
private function _add_url($url)
{
- debug_event("stream_playlist.class.php", "Adding url {".json_encode($url)."}...", 5);
+ debug_event("stream_playlist.class.php", "Adding url {" . json_encode($url) . "}...", 5);
$this->urls[] = $url;
- $sql = 'INSERT INTO `stream_playlist` ';
+ $sql = 'INSERT INTO `stream_playlist` ';
- $fields = array();
- $fields[] = '`sid`';
- $values = array();
- $values[] = $this->id;
- $holders = array();
+ $fields = array();
+ $fields[] = '`sid`';
+ $values = array();
+ $values[] = $this->id;
+ $holders = array();
$holders[] = '?';
foreach ($url->properties as $field) {
if ($url->$field) {
- $fields[] = '`' . $field . '`';
+ $fields[] = '`' . $field . '`';
$holders[] = '?';
- $values[] = $url->$field;
+ $values[] = $url->$field;
}
}
$sql .= '(' . implode(', ', $fields) . ') ';
@@ -108,75 +110,120 @@ class Stream_Playlist
{
$urls = array();
foreach ($media as $medium) {
- $url = array();
-
- if ($medium['custom_play_action']) {
- $additional_params .= "&custom_play_action=" . $medium['custom_play_action'];
- }
-
- if ($_SESSION['iframe']['subtitle']) {
- $additional_params .= "&subtitle=" . $_SESSION['iframe']['subtitle'];
- }
-
- $type = $medium['object_type'];
- $object_id = $medium['object_id'];
- $url['type'] = $type;
-
- $object = new $type($object_id);
- $object->format();
- // Don't add disabled media objects to the stream playlist
- // Playing a disabled media return a 404 error that could make failed the player (mpd ...)
- if (!isset($object->enabled) || make_bool($object->enabled)) {
- //FIXME: play_url shouldn't be static
- $url['url'] = $type::play_url($object->id, $additional_params);
-
- $api_session = (AmpConfig::get('require_session')) ? Stream::get_session() : false;
-
- // Set a default which can be overridden
- $url['author'] = 'Ampache';
- $url['time'] = $object->time;
- switch ($type) {
- case 'song':
- $url['title'] = $object->title;
- $url['author'] = $object->f_artist_full;
- $url['info_url'] = $object->f_link;
- $url['image_url'] = Art::url($object->album, 'album', $api_session, (AmpConfig::get('ajax_load') ? 3 : 4));
- $url['album'] = $object->f_album_full;
- break;
- case 'video':
- $url['title'] = 'Video - ' . $object->title;
- $url['author'] = $object->f_artist_full;
- $url['resolution'] = $object->f_resolution;
- break;
- case 'live_stream':
- $url['title'] = 'Radio - ' . $object->name;
- if (!empty($object->site_url)) {
- $url['title'] .= ' (' . $object->site_url . ')';
- }
- $url['codec'] = $object->codec;
- break;
- case 'song_preview':
- $url['title'] = $object->title;
- $url['author'] = $object->f_artist_full;
- break;
- case 'channel':
- $url['title'] = $object->name;
- break;
- case 'random':
- $url['title'] = 'Random URL';
- break;
- default:
- $url['title'] = 'URL-Add';
- $url['time'] = -1;
- break;
- }
-
- $urls[] = new Stream_URL($url);
+ $surl = self::media_to_url($medium, $additional_params);
+ if ($surl != null) {
+ $urls[] = $surl;
}
}
return $urls;
}
+
+ /**
+ * media_to_url
+ */
+ public static function media_to_url($media, $additional_params='', $urltype='web')
+ {
+ $type = $media['object_type'];
+ $object_id = $media['object_id'];
+ $object = new $type($object_id);
+ $object->format();
+
+ if ($media['custom_play_action']) {
+ $additional_params .= "&custom_play_action=" . $media['custom_play_action'];
+ }
+
+ if ($_SESSION['iframe']['subtitle']) {
+ $additional_params .= "&subtitle=" . $_SESSION['iframe']['subtitle'];
+ }
+
+ return self::media_object_to_url($object, $additional_params, $urltype);
+ }
+
+ /**
+ * media_object_to_url
+ */
+ public static function media_object_to_url($object, $additional_params='', $urltype='web')
+ {
+ $surl = null;
+ $url = array();
+
+ $type = strtolower(get_class($object));
+ $url['type'] = $type;
+
+ // Don't add disabled media objects to the stream playlist
+ // Playing a disabled media return a 404 error that could make failed the player (mpd ...)
+ if (!isset($object->enabled) || make_bool($object->enabled)) {
+ if ($urltype == 'file') {
+ $url['url'] = $object->file;
+ // Relative path
+ if (!empty($additional_params) && strpos($url['url'], $additional_params) === 0) {
+ $url['url'] = substr($url['url'], strlen($additional_params));
+ if (strlen($url['url']) < 1) {
+ return null;
+ }
+ if ($url['url'][0] == DIRECTORY_SEPARATOR) {
+ $url['url'] = substr($url['url'], 1);
+ }
+ }
+ } else {
+ //FIXME: play_url shouldn't be static
+ $url['url'] = $type::play_url($object->id, $additional_params);
+ }
+
+ $api_session = (AmpConfig::get('require_session')) ? Stream::get_session() : false;
+
+ // Set a default which can be overridden
+ $url['author'] = 'Ampache';
+ $url['time'] = $object->time;
+ switch ($type) {
+ case 'song':
+ $url['title'] = $object->title;
+ $url['author'] = $object->f_artist_full;
+ $url['info_url'] = $object->f_link;
+ $url['image_url'] = Art::url($object->album, 'album', $api_session, (AmpConfig::get('ajax_load') ? 3 : 4));
+ $url['album'] = $object->f_album_full;
+ $url['track_num'] = $object->f_track;
+ break;
+ case 'video':
+ $url['title'] = 'Video - ' . $object->title;
+ $url['author'] = $object->f_artist_full;
+ $url['resolution'] = $object->f_resolution;
+ break;
+ case 'live_stream':
+ $url['title'] = 'Radio - ' . $object->name;
+ if (!empty($object->site_url)) {
+ $url['title'] .= ' (' . $object->site_url . ')';
+ }
+ $url['codec'] = $object->codec;
+ break;
+ case 'song_preview':
+ $url['title'] = $object->title;
+ $url['author'] = $object->f_artist_full;
+ break;
+ case 'channel':
+ $url['title'] = $object->name;
+ break;
+ case 'podcast_episode':
+ $url['title'] = $object->f_title;
+ $url['author'] = $object->f_podcast;
+ $url['info_url'] = $object->f_link;
+ $url['image_url'] = Art::url($object->podcast, 'podcast', $api_session, (AmpConfig::get('ajax_load') ? 3 : 4));
+ break;
+ case 'random':
+ $url['title'] = 'Random URL';
+ break;
+ default:
+ $url['title'] = 'URL-Add';
+ $url['time'] = -1;
+ break;
+ }
+
+ $surl = new Stream_URL($url);
+ }
+
+ return $surl;
+ }
public static function check_autoplay_append()
{
@@ -199,7 +246,7 @@ class Stream_Playlist
return false;
}
- debug_event('stream_playlist', 'Generating a {'.$type.'} object...', 5);
+ debug_event('stream_playlist', 'Generating a {' . $type . '} object...', 5);
$ext = $type;
switch ($type) {
@@ -208,7 +255,7 @@ class Stream_Playlist
case 'localplay':
case 'web_player':
// These are valid, but witchy
- $ct = "";
+ $ct = "";
$redirect = false;
unset($ext);
break;
@@ -223,20 +270,20 @@ class Stream_Playlist
break;
case 'simple_m3u':
$ext = 'm3u';
- $ct = 'audio/x-mpegurl';
+ $ct = 'audio/x-mpegurl';
break;
case 'xspf':
$ct = 'application/xspf+xml';
break;
case 'hls':
$ext = 'm3u8';
- $ct = 'application/vnd.apple.mpegurl';
+ $ct = 'application/vnd.apple.mpegurl';
break;
case 'm3u':
default:
// Assume M3U if the pooch is screwed
$ext = $type = 'm3u';
- $ct = 'audio/x-mpegurl';
+ $ct = 'audio/x-mpegurl';
break;
}
@@ -275,7 +322,9 @@ class Stream_Playlist
*/
public function add_urls($urls = array())
{
- if (!is_array($urls)) { return false; }
+ if (!is_array($urls)) {
+ return false;
+ }
foreach ($urls as $url) {
$this->_add_url(new Stream_URL(array(
@@ -296,77 +345,92 @@ class Stream_Playlist
foreach ($this->urls as $url) {
echo $url->url . "\n";
}
-
} // simple_m3u
/**
- * create_m3u
+ * get_m3u_string
* creates an m3u file, this includes the EXTINFO and as such can be
* large with very long playlists
*/
+ public function get_m3u_string()
+ {
+ $ret = "#EXTM3U\n";
+
+ $i = 0;
+ foreach ($this->urls as $url) {
+ $ret .= '#EXTINF:' . $url->time . ',' . $url->author . ' - ' . $url->title . "\n";
+ $ret .= $url->url . "\n";
+ $i++;
+ }
+ return $ret;
+ } // get_m3u_string
+
public function create_m3u()
{
- echo "#EXTM3U\n";
-
- $i = 0;
- foreach ($this->urls as $url) {
- echo '#EXTINF:' . $url->time, ',' . $url->author . ' - ' . $url->title . "\n";
- echo $url->url . "\n";
- $i++;
- }
-
- } // create_m3u
+ echo $this->get_m3u_string();
+ }
/**
- * create_pls
+ * get_pls_string
*/
+ public function get_pls_string()
+ {
+ $ret = "[playlist]\n";
+ $ret .= 'NumberOfEntries=' . count($this->urls) . "\n";
+ $i = 0;
+ foreach ($this->urls as $url) {
+ $i++;
+ $ret .= 'File' . $i . '=' . $url->url . "\n";
+ $ret .= 'Title' . $i . '=' . $url->author . ' - ' .
+ $url->title . "\n";
+ $ret .= 'Length' . $i . '=' . $url->time . "\n";
+ }
+
+ $ret .= "Version=2\n";
+ return $ret;
+ } // get_pls_string
+
public function create_pls()
{
- echo "[playlist]\n";
- echo 'NumberOfEntries=' . count($this->urls) . "\n";
- $i = 0;
- foreach ($this->urls as $url) {
- $i++;
- echo 'File' . $i . '='. $url->url . "\n";
- echo 'Title' . $i . '=' . $url->author . ' - ' .
- $url->title . "\n";
- echo 'Length' . $i . '=' . $url->time . "\n";
- }
-
- echo "Version=2\n";
- } // create_pls
+ echo $this->get_pls_string();
+ }
/**
- * create_asx
+ * get_asx_string
* This should really only be used if all of the content is ASF files.
*/
- public function create_asx()
+ public function get_asx_string()
{
- echo '' . "\n";
- echo "Ampache ASX Playlist\n";
- echo '' . "\n";
+ $ret = '' . "\n";
+ $ret .= "" . ($this->title ?: "Ampache ASX Playlist") . "\n";
+ $ret .= '' . "\n";
foreach ($this->urls as $url) {
- echo "\n";
- echo '' . scrub_out($url->title) . "\n";
- echo '' . scrub_out($url->author) . "\n";
+ $ret .= "\n";
+ $ret .= '' . scrub_out($url->title) . "\n";
+ $ret .= '' . scrub_out($url->author) . "\n";
//FIXME: duration looks hacky and wrong
- echo "\t\t" . '' . "\n";
- echo "\t\t" . '' . "\n";
- echo "\t\t" . '' . "\n";
- echo "\t\t" . '' . "\n";
- echo '' . "\n";
- echo "\n";
+ $ret .= "\t\t" . '' . "\n";
+ $ret .= "\t\t" . '' . "\n";
+ $ret .= "\t\t" . '' . "\n";
+ $ret .= "\t\t" . '' . "\n";
+ $ret .= '' . "\n";
+ $ret .= "\n";
}
- echo "\n";
+ $ret .= "\n";
+ return $ret;
+ } // get_asx_string
- } // create_asx
+ public function create_asx()
+ {
+ echo $this->get_asx_string();
+ }
/**
- * create_xspf
+ * get_xspf_string
*/
- public function create_xspf()
+ public function get_xspf_string()
{
$result = "";
foreach ($this->urls as $url) {
@@ -395,38 +459,45 @@ class Stream_Playlist
if ($url->album) {
$xml['track']['album'] = $url->album;
}
+ if ($url->track_num) {
+ $xml['track']['trackNum'] = $url->track_num;
+ }
$result .= XML_Data::keyed_array($xml, true);
-
} // end foreach
XML_Data::set_type('xspf');
- echo XML_Data::header();
- echo $result;
- echo XML_Data::footer();
+ $ret = XML_Data::header($this->title);
+ $ret .= $result;
+ $ret .= XML_Data::footer();
+ return $ret;
+ } // get_xspf_string
- } // create_xspf
+ public function create_xspf()
+ {
+ echo $this->get_xspf_string();
+ }
- public function create_hls()
+ public function get_hls_string()
{
$ssize = 10;
- echo "#EXTM3U\n";
- echo "#EXT-X-TARGETDURATION:" . $ssize . "\n";
- echo "#EXT-X-VERSION:1\n";
- echo "#EXT-X-ALLOW-CACHE:NO\n";
- echo "#EXT-X-MEDIA-SEQUENCE:0\n";
- echo "#EXT-X-PLAYLIST-TYPE:VOD\n"; // Static list of segments
+ $ret = "#EXTM3U\n";
+ $ret .= "#EXT-X-TARGETDURATION:" . $ssize . "\n";
+ $ret .= "#EXT-X-VERSION:1\n";
+ $ret .= "#EXT-X-ALLOW-CACHE:NO\n";
+ $ret .= "#EXT-X-MEDIA-SEQUENCE:0\n";
+ $ret .= "#EXT-X-PLAYLIST-TYPE:VOD\n"; // Static list of segments
foreach ($this->urls as $url) {
$soffset = 0;
$segment = 0;
while ($soffset < $url->time) {
- $type = $url->type;
- $size = (($soffset + $ssize) <= $url->time) ? $ssize : ($url->time - $soffset);
+ $type = $url->type;
+ $size = (($soffset + $ssize) <= $url->time) ? $ssize : ($url->time - $soffset);
$additional_params = '&transcode_to=ts&segment=' . $segment;
- echo "#EXTINF:" . $size . ",\n";
+ $ret .= "#EXTINF:" . $size . ",\n";
$purl = Stream_URL::parse($url->url);
- $id = $purl['id'];
+ $id = $purl['id'];
unset($purl['id']);
unset($purl['ssid']);
@@ -440,13 +511,19 @@ class Stream_Playlist
}
$hu = $type::play_url($id, $additional_params);
- echo $hu . "\n";
+ $ret .= $hu . "\n";
$soffset += $size;
$segment++;
}
}
- echo "#EXT-X-ENDLIST\n\n";
+ $ret .= "#EXT-X-ENDLIST\n\n";
+ return $ret;
+ }
+
+ public function create_hls()
+ {
+ echo $this->get_hls_string();
}
/**
@@ -457,11 +534,10 @@ class Stream_Playlist
public function create_web_player()
{
if (AmpConfig::get("ajax_load")) {
- require AmpConfig::get('prefix') . '/templates/create_web_player_embedded.inc.php';
+ require AmpConfig::get('prefix') . UI::find_template('create_web_player_embedded.inc.php');
} else {
- require AmpConfig::get('prefix') . '/templates/create_web_player.inc.php';
+ require AmpConfig::get('prefix') . UI::find_template('create_web_player.inc.php');
}
-
} // create_web_player
/**
@@ -492,7 +568,6 @@ class Stream_Playlist
}
$localplay->play();
}
-
} // create_localplay
/**
@@ -508,7 +583,7 @@ class Stream_Playlist
$items = array();
foreach ($this->urls as $url) {
- $data = Stream_URL::parse($url->url);
+ $data = Stream_URL::parse($url->url);
$items[] = array($data['type'], $data['id']);
}
diff --git a/sources/lib/class/stream_url.class.php b/sources/lib/class/stream_url.class.php
index 019d8c1..4b322c0 100644
--- a/sources/lib/class/stream_url.class.php
+++ b/sources/lib/class/stream_url.class.php
@@ -2,22 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; version 2
- * of the License.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -25,7 +24,7 @@
class Stream_URL extends memory_object
{
- public $properties = array('url', 'title', 'author', 'time', 'info_url', 'image_url', 'album', 'type', 'codec');
+ public $properties = array('url', 'title', 'author', 'time', 'info_url', 'image_url', 'album', 'type', 'codec', 'track_num');
/**
* parse
@@ -38,19 +37,20 @@ class Stream_URL extends memory_object
$posargs = strpos($url, '/play/');
if ($posargs !== false) {
$argsstr = substr($url, $posargs + 6);
- $url = substr($url, 0, $posargs + 6) . 'index.php?';
- $args = explode('/', $argsstr);
+ $url = substr($url, 0, $posargs + 6) . 'index.php?';
+ $args = explode('/', $argsstr);
for ($i = 0; $i < count($args); $i += 2) {
- if ($i > 0)
+ if ($i > 0) {
$url .= '&';
+ }
$url .= $args[$i] . '=' . $args[$i + 1];
}
}
}
- $query = parse_url($url, PHP_URL_QUERY);
+ $query = parse_url($url, PHP_URL_QUERY);
$elements = explode('&', $query);
- $results = array();
+ $results = array();
$results['base_url'] = $url;
diff --git a/sources/lib/class/subsonic_api.class.php b/sources/lib/class/subsonic_api.class.php
index 07584a0..0e32b36 100644
--- a/sources/lib/class/subsonic_api.class.php
+++ b/sources/lib/class/subsonic_api.class.php
@@ -2,22 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; version 2
- * of the License.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -54,7 +53,9 @@ class Subsonic_Api
{
if (empty($input[$parameter])) {
ob_end_clean();
- if ($addheader) self::setHeader($input['f']);
+ if ($addheader) {
+ self::setHeader($input['f']);
+ }
self::apiOutput($input, Subsonic_XML_Data::createError(Subsonic_XML_Data::SSERROR_MISSINGPARAM));
exit;
}
@@ -67,9 +68,11 @@ class Subsonic_Api
// Decode hex-encoded password
$encpwd = strpos($password, "enc:");
if ($encpwd !== false) {
- $hex = substr($password, 4);
+ $hex = substr($password, 4);
$decpwd = '';
- for ($i=0; $i 1) {
if ($rhpart[0] != "Transfer-Encoding") {
header($rheader);
@@ -105,9 +108,10 @@ class Subsonic_Api
set_time_limit(0);
ob_end_clean();
+ header("Access-Control-Allow-Origin: *");
if (function_exists('curl_version')) {
- $headers = apache_request_headers();
- $reqheaders = array();
+ $headers = apache_request_headers();
+ $reqheaders = array();
$reqheaders[] = "User-Agent: " . $headers['User-Agent'];
if (isset($headers['Range'])) {
$reqheaders[] = "Range: " . $headers['Range'];
@@ -145,17 +149,19 @@ class Subsonic_Api
{
if (strtolower($f) == "json") {
header("Content-type: application/json; charset=" . AmpConfig::get('site_charset'));
- } else if (strtolower($f) == "jsonp") {
+ Subsonic_XML_Data::$enable_json_checks = true;
+ } elseif (strtolower($f) == "jsonp") {
header("Content-type: text/javascript; charset=" . AmpConfig::get('site_charset'));
+ Subsonic_XML_Data::$enable_json_checks = true;
} else {
header("Content-type: text/xml; charset=" . AmpConfig::get('site_charset'));
}
- header("access-control-allow-origin: *");
+ header("Access-Control-Allow-Origin: *");
}
public static function apiOutput($input, $xml)
{
- $f = $input['f'];
+ $f = $input['f'];
$callback = $input['callback'];
self::apiOutput2(strtolower($f), $xml, $callback);
}
@@ -163,17 +169,21 @@ class Subsonic_Api
public static function apiOutput2($f, $xml, $callback='')
{
if ($f == "json") {
- echo json_encode(self::xml2json($xml), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
- } else if ($f == "jsonp") {
- echo $callback . '(' . json_encode(self::xml2json($xml), JSON_PRETTY_PRINT) . ')';
+ $output = json_encode(self::xml2json($xml), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
} else {
- $xmlstr = $xml->asXml();
- // Format xml output
- $dom = new DOMDocument();
- $dom->loadXML($xmlstr);
- $dom->formatOutput = true;
- echo $dom->saveXML();
+ if ($f == "jsonp") {
+ $output = $callback . '(' . json_encode(self::xml2json($xml), JSON_PRETTY_PRINT) . ')';
+ } else {
+ $xmlstr = $xml->asXml();
+ // Format xml output
+ $dom = new DOMDocument();
+ $dom->loadXML($xmlstr);
+ $dom->formatOutput = true;
+ $output = $dom->saveXML();
+ }
}
+
+ echo $output;
}
/**
@@ -187,14 +197,14 @@ class Subsonic_Api
'attributePrefix' => '', //to distinguish between attributes and nodes with the same name
'alwaysArray' => array(), //array of xml tag names which should always become arrays
'autoArray' => true, //only create arrays for tags which appear more than once
- 'textContent' => '$', //key used for the text content of elements
+ 'textContent' => 'value', //key used for the text content of elements
'autoText' => true, //skip textContent key if node has no attributes or child nodes
'keySearch' => false, //optional search and replace on tag and attribute names
'keyReplace' => false, //replace values for above search values (as passed to str_replace())
'boolean' => true //replace true and false string with boolean values
);
- $options = array_merge($defaults, $options);
- $namespaces = $xml->getDocNamespaces();
+ $options = array_merge($defaults, $options);
+ $namespaces = $xml->getDocNamespaces();
$namespaces[''] = null; //add base (empty) namespace
//get attributes from all namespaces
@@ -202,8 +212,10 @@ class Subsonic_Api
foreach ($namespaces as $prefix => $namespace) {
foreach ($xml->attributes($namespace) as $attributeName => $attribute) {
//replace characters in attribute name
- if ($options['keySearch']) $attributeName =
+ if ($options['keySearch']) {
+ $attributeName =
str_replace($options['keySearch'], $options['keyReplace'], $attributeName);
+ }
$attributeKey = $options['attributePrefix']
. ($prefix ? $prefix . $options['namespaceSeparator'] : '')
. $attributeName;
@@ -222,14 +234,18 @@ class Subsonic_Api
foreach ($namespaces as $prefix => $namespace) {
foreach ($xml->children($namespace) as $childXml) {
//recurse into child nodes
- $childArray = self::xml2json($childXml, $options);
+ $childArray = self::xml2json($childXml, $options);
list($childTagName, $childProperties) = each($childArray);
//replace characters in tag name
- if ($options['keySearch']) $childTagName =
+ if ($options['keySearch']) {
+ $childTagName =
str_replace($options['keySearch'], $options['keyReplace'], $childTagName);
+ }
//add namespace prefix, if any
- if ($prefix) $childTagName = $prefix . $options['namespaceSeparator'] . $childTagName;
+ if ($prefix) {
+ $childTagName = $prefix . $options['namespaceSeparator'] . $childTagName;
+ }
if (!isset($tagsArray[$childTagName])) {
//only entry with this key
@@ -252,8 +268,10 @@ class Subsonic_Api
//get text content of node
$textContentArray = array();
- $plainText = trim((string) $xml);
- if ($plainText !== '') $textContentArray[$options['textContent']] = $plainText;
+ $plainText = trim((string) $xml);
+ if ($plainText !== '') {
+ $textContentArray[$options['textContent']] = $plainText;
+ }
//stick it all together
$propertiesArray = !$options['autoText'] || $attributesArray || $tagsArray || ($plainText === '')
@@ -302,12 +320,12 @@ class Subsonic_Api
*/
public static function getmusicfolders($input)
{
- self::check_version($input);
+ self::check_version($input);
- $r = Subsonic_XML_Data::createSuccessResponse();
- Subsonic_XML_Data::addMusicFolders($r, Catalog::get_catalogs());
- self::apiOutput($input, $r);
- }
+ $r = Subsonic_XML_Data::createSuccessResponse();
+ Subsonic_XML_Data::addMusicFolders($r, Catalog::get_catalogs());
+ self::apiOutput($input, $r);
+ }
/**
* getIndexes
@@ -316,41 +334,54 @@ class Subsonic_Api
*/
public static function getindexes($input)
{
- self::check_version($input);
+ self::check_version($input);
+ set_time_limit(300);
- $musicFolderId = $input['musicFolderId'];
- $ifModifiedSince = $input['ifModifiedSince'];
+ $musicFolderId = $input['musicFolderId'];
+ $ifModifiedSince = $input['ifModifiedSince'];
- $catalogs = array();
- if (!empty($musicFolderId) && $musicFolderId != '-1') {
- $catalogs[] = $musicFolderId;
- } else {
- $catalogs = Catalog::get_catalogs();
- }
+ $catalogs = array();
+ if (!empty($musicFolderId) && $musicFolderId != '-1') {
+ $catalogs[] = $musicFolderId;
+ } else {
+ $catalogs = Catalog::get_catalogs();
+ }
- $lastmodified = 0;
- $fcatalogs = array();
+ $lastmodified = 0;
+ $fcatalogs = array();
- foreach ($catalogs as $id) {
- $clastmodified = 0;
- $catalog = Catalog::create_from_id($id);
+ foreach ($catalogs as $id) {
+ $clastmodified = 0;
+ $catalog = Catalog::create_from_id($id);
- if ($catalog->last_update > $clastmodified) $clastmodified = $catalog->last_update;
- if ($catalog->last_add > $clastmodified) $clastmodified = $catalog->last_add;
- if ($catalog->last_clean > $clastmodified) $clastmodified = $catalog->last_clean;
+ if ($catalog->last_update > $clastmodified) {
+ $clastmodified = $catalog->last_update;
+ }
+ if ($catalog->last_add > $clastmodified) {
+ $clastmodified = $catalog->last_add;
+ }
+ if ($catalog->last_clean > $clastmodified) {
+ $clastmodified = $catalog->last_clean;
+ }
- if ($clastmodified > $lastmodified) $lastmodified = $clastmodified;
- if (!empty($ifModifiedSince) && $clastmodified > ($ifModifiedSince / 1000)) $fcatalogs[] = $id;
- }
- if (empty($ifModifiedSince)) $fcatalogs = $catalogs;
+ if ($clastmodified > $lastmodified) {
+ $lastmodified = $clastmodified;
+ }
+ if (!empty($ifModifiedSince) && $clastmodified > ($ifModifiedSince / 1000)) {
+ $fcatalogs[] = $id;
+ }
+ }
+ if (empty($ifModifiedSince)) {
+ $fcatalogs = $catalogs;
+ }
- $r = Subsonic_XML_Data::createSuccessResponse();
- if (count($fcatalogs) > 0) {
- $artists = Catalog::get_artists($fcatalogs);
- Subsonic_XML_Data::addArtistsIndexes($r, $artists, $lastmodified);
- }
- self::apiOutput($input, $r);
- }
+ $r = Subsonic_XML_Data::createSuccessResponse();
+ if (count($fcatalogs) > 0) {
+ $artists = Catalog::get_artists($fcatalogs);
+ Subsonic_XML_Data::addArtistsIndexes($r, $artists, $lastmodified);
+ }
+ self::apiOutput($input, $r);
+ }
/**
* getMusicDirectory
@@ -359,19 +390,21 @@ class Subsonic_Api
*/
public static function getmusicdirectory($input)
{
- self::check_version($input);
+ self::check_version($input);
- $id = self::check_parameter($input, 'id');
+ $id = self::check_parameter($input, 'id');
- $r = Subsonic_XML_Data::createSuccessResponse();
- if (Subsonic_XML_Data::isArtist($id)) {
- $artist = new Artist(Subsonic_XML_Data::getAmpacheId($id));
- Subsonic_XML_Data::addArtistDirectory($r, $artist);
- } else if (Subsonic_XML_Data::isAlbum($id)) {
- $album = new Album(Subsonic_XML_Data::getAmpacheId($id));
- Subsonic_XML_Data::addAlbumDirectory($r, $album);
- }
- self::apiOutput($input, $r);
+ $r = Subsonic_XML_Data::createSuccessResponse();
+ if (Subsonic_XML_Data::isArtist($id)) {
+ $artist = new Artist(Subsonic_XML_Data::getAmpacheId($id));
+ Subsonic_XML_Data::addArtistDirectory($r, $artist);
+ } else {
+ if (Subsonic_XML_Data::isAlbum($id)) {
+ $album = new Album(Subsonic_XML_Data::getAmpacheId($id));
+ Subsonic_XML_Data::addAlbumDirectory($r, $album);
+ }
+ }
+ self::apiOutput($input, $r);
}
/**
@@ -397,9 +430,9 @@ class Subsonic_Api
{
self::check_version($input, "1.7.0");
- $r = Subsonic_XML_Data::createSuccessResponse();
+ $r = Subsonic_XML_Data::createSuccessResponse();
$artists = Catalog::get_artists(Catalog::get_catalogs());
- Subsonic_XML_Data::addArtistsRoot($r, $artists);
+ Subsonic_XML_Data::addArtistsRoot($r, $artists, true);
self::apiOutput($input, $r);
}
@@ -435,12 +468,14 @@ class Subsonic_Api
$albumid = self::check_parameter($input, 'id');
+ $addAmpacheInfo = ($input['ampache'] == "1");
+
$album = new Album(Subsonic_XML_Data::getAmpacheId($albumid));
if (empty($album->name)) {
$r = Subsonic_XML_Data::createError(Subsonic_XML_Data::SSERROR_DATA_NOTFOUND, "Album not found.");
} else {
$r = Subsonic_XML_Data::createSuccessResponse();
- Subsonic_XML_Data::addAlbum($r, $album, true);
+ Subsonic_XML_Data::addAlbum($r, $album, true, $addAmpacheInfo);
}
self::apiOutput($input, $r);
@@ -455,7 +490,7 @@ class Subsonic_Api
{
self::check_version($input, "1.7.0");
- $r = Subsonic_XML_Data::createSuccessResponse();
+ $r = Subsonic_XML_Data::createSuccessResponse();
$videos = Catalog::get_videos();
Subsonic_XML_Data::addVideos($r, $videos);
self::apiOutput($input, $r);
@@ -472,77 +507,97 @@ class Subsonic_Api
$type = self::check_parameter($input, 'type');
- $size = $input['size'];
- $offset = $input['offset'];
+ $size = $input['size'];
+ $offset = $input['offset'];
$musicFolderId = $input['musicFolderId'] ?: 0;
// Get albums from all catalogs by default
// Catalog filter is not supported for all request type for now.
$catalogs = null;
if ($musicFolderId > 0) {
- $catalogs = array();
+ $catalogs = array();
$catalogs[] = $musicFolderId;
}
-
- $albums = array();
+
+ $r = Subsonic_XML_Data::createSuccessResponse();
+ $errorOccured = false;
+ $albums = array();
+
if ($type == "random") {
$albums = Album::get_random($size);
- } else if ($type == "newest") {
- $albums = Stats::get_newest("album", $size, $offset, $musicFolderId);
- } else if ($type == "highest") {
- $albums = Rating::get_highest("album", $size, $offset);
- } else if ($type == "frequent") {
- $albums = Stats::get_top("album", $size, '', $offset);
- } else if ($type == "recent") {
- $albums = Stats::get_recent("album", $size, $offset);
- } else if ($type == "starred") {
- $albums = Userflag::get_latest('album');
- } else if ($type == "alphabeticalByName") {
- $albums = Catalog::get_albums($size, $offset, $catalogs);
- } else if ($type == "alphabeticalByArtist") {
- $albums = Catalog::get_albums_by_artist($size, $offset, $catalogs);
- } else if ($type == "byYear") {
- $fromYear = $input['fromYear'];
- $toYear = $input['toYear'];
-
- if ($fromYear || $toYear) {
- $search = array();
- $search['limit'] = $size;
- $search['offset'] = $offset;
- $search['type'] = "album";
- $i = 0;
- if ($fromYear) {
- $search['rule_'.$i.'_input'] = $fromYear;
- $search['rule_'.$i.'_operator'] = 0;
- $search['rule_'.$i.''] = "year";
- ++$i;
- }
- if ($toYear) {
- $search['rule_'.$i.'_input'] = $toYear;
- $search['rule_'.$i.'_operator'] = 1;
- $search['rule_'.$i.''] = "year";
- ++$i;
- }
-
- $query = new Search(null, 'album');
- $albums = $query->run($search);
- }
- } else if ($type == "byGenre") {
- $genre = self::check_parameter($input, 'genre');
-
- $tag_id = Tag::tag_exists($genre);
- if ($tag_id) {
- $albums = Tag::get_tag_objects('album', $tag_id, $size, $offset);
- }
- }
-
- if (count($albums)) {
- $r = Subsonic_XML_Data::createSuccessResponse();
- Subsonic_XML_Data::addAlbumList($r, $albums, $elementName);
} else {
- $r = Subsonic_XML_Data::createError(Subsonic_XML_Data::SSERROR_DATA_NOTFOUND);
+ if ($type == "newest") {
+ $albums = Stats::get_newest("album", $size, $offset, $musicFolderId);
+ } else {
+ if ($type == "highest") {
+ $albums = Rating::get_highest("album", $size, $offset);
+ } else {
+ if ($type == "frequent") {
+ $albums = Stats::get_top("album", $size, '', $offset);
+ } else {
+ if ($type == "recent") {
+ $albums = Stats::get_recent("album", $size, $offset);
+ } else {
+ if ($type == "starred") {
+ $albums = Userflag::get_latest('album');
+ } else {
+ if ($type == "alphabeticalByName") {
+ $albums = Catalog::get_albums($size, $offset, $catalogs);
+ } else {
+ if ($type == "alphabeticalByArtist") {
+ $albums = Catalog::get_albums_by_artist($size, $offset, $catalogs);
+ } else {
+ if ($type == "byYear") {
+ $fromYear = $input['fromYear'];
+ $toYear = $input['toYear'];
+
+ if ($fromYear || $toYear) {
+ $search = array();
+ $search['limit'] = $size;
+ $search['offset'] = $offset;
+ $search['type'] = "album";
+ $i = 0;
+ if ($fromYear) {
+ $search['rule_' . $i . '_input'] = $fromYear;
+ $search['rule_' . $i . '_operator'] = 0;
+ $search['rule_' . $i . ''] = "year";
+ ++$i;
+ }
+ if ($toYear) {
+ $search['rule_' . $i . '_input'] = $toYear;
+ $search['rule_' . $i . '_operator'] = 1;
+ $search['rule_' . $i . ''] = "year";
+ ++$i;
+ }
+
+ $query = new Search(null, 'album');
+ $albums = $query->run($search);
+ }
+ } else {
+ if ($type == "byGenre") {
+ $genre = self::check_parameter($input, 'genre');
+
+ $tag_id = Tag::tag_exists($genre);
+ if ($tag_id) {
+ $albums = Tag::get_tag_objects('album', $tag_id, $size, $offset);
+ }
+ } else {
+ $r = Subsonic_XML_Data::createError(Subsonic_XML_Data::SSERROR_GENERIC, "Invalid list type: " . scrub_out($type));
+ $errorOccured = true;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
}
+ if (!$errorOccured) {
+ Subsonic_XML_Data::addAlbumList($r, $albums, $elementName);
+ }
self::apiOutput($input, $r);
}
@@ -566,54 +621,58 @@ class Subsonic_Api
self::check_version($input, "1.2.0");
$size = $input['size'];
- if (!$size) $size = 10;
- $genre = $input['genre'];
- $fromYear = $input['fromYear'];
- $toYear = $input['toYear'];
+ if (!$size) {
+ $size = 10;
+ }
+ $genre = $input['genre'];
+ $fromYear = $input['fromYear'];
+ $toYear = $input['toYear'];
$musicFolderId = $input['musicFolderId'];
- $search = array();
- $search['limit'] = $size;
+ $search = array();
+ $search['limit'] = $size;
$search['random'] = $size;
- $search['type'] = "song";
- $i = 0;
+ $search['type'] = "song";
+ $i = 0;
if ($genre) {
- $search['rule_'.$i.'_input'] = $genre;
- $search['rule_'.$i.'_operator'] = 0;
- $search['rule_'.$i.''] = "tag";
+ $search['rule_' . $i . '_input'] = $genre;
+ $search['rule_' . $i . '_operator'] = 0;
+ $search['rule_' . $i . ''] = "tag";
++$i;
}
if ($fromYear) {
- $search['rule_'.$i.'_input'] = $fromYear;
- $search['rule_'.$i.'_operator'] = 0;
- $search['rule_'.$i.''] = "year";
+ $search['rule_' . $i . '_input'] = $fromYear;
+ $search['rule_' . $i . '_operator'] = 0;
+ $search['rule_' . $i . ''] = "year";
++$i;
}
if ($toYear) {
- $search['rule_'.$i.'_input'] = $toYear;
- $search['rule_'.$i.'_operator'] = 1;
- $search['rule_'.$i.''] = "year";
+ $search['rule_' . $i . '_input'] = $toYear;
+ $search['rule_' . $i . '_operator'] = 1;
+ $search['rule_' . $i . ''] = "year";
++$i;
}
if ($musicFolderId) {
if (Subsonic_XML_Data::isArtist($musicFolderId)) {
- $artist = new Artist(Subsonic_XML_Data::getAmpacheId($musicFolderId));
- $finput = $artist->name;
+ $artist = new Artist(Subsonic_XML_Data::getAmpacheId($musicFolderId));
+ $finput = $artist->name;
$operator = 4;
- $ftype = "artist";
- } else if (Subsonic_XML_Data::isAlbum($musicFolderId)) {
- $album = new Album(Subsonic_XML_Data::getAmpacheId($musicFolderId));
- $finput = $album->name;
- $operator = 4;
- $ftype = "artist";
+ $ftype = "artist";
} else {
- $finput = intval($musicFolderId);
- $operator = 0;
- $ftype = "catalog";
+ if (Subsonic_XML_Data::isAlbum($musicFolderId)) {
+ $album = new Album(Subsonic_XML_Data::getAmpacheId($musicFolderId));
+ $finput = $album->name;
+ $operator = 4;
+ $ftype = "artist";
+ } else {
+ $finput = intval($musicFolderId);
+ $operator = 0;
+ $ftype = "catalog";
+ }
}
- $search['rule_'.$i.'_input'] = $finput;
- $search['rule_'.$i.'_operator'] = $operator;
- $search['rule_'.$i.''] = $ftype;
+ $search['rule_' . $i . '_input'] = $finput;
+ $search['rule_' . $i . '_operator'] = $operator;
+ $search['rule_' . $i . ''] = $ftype;
++$i;
}
if ($i > 0) {
@@ -637,8 +696,8 @@ class Subsonic_Api
self::check_version($input, "1.7.0");
$songid = self::check_parameter($input, 'id');
- $r = Subsonic_XML_Data::createSuccessResponse();
- $song = new Song(Subsonic_XML_Data::getAmpacheId($songid));
+ $r = Subsonic_XML_Data::createSuccessResponse();
+ $song = new Song(Subsonic_XML_Data::getAmpacheId($songid));
Subsonic_XML_Data::addSong($r, $song);
self::apiOutput($input, $r);
}
@@ -652,8 +711,8 @@ class Subsonic_Api
{
self::check_version($input, "1.9.0");
- $genre = self::check_parameter($input, 'genre');
- $count = $input['count'];
+ $genre = self::check_parameter($input, 'genre');
+ $count = $input['count'];
$offset = $input['offset'];
$tag = Tag::construct_from_name($genre);
@@ -677,7 +736,7 @@ class Subsonic_Api
self::check_version($input);
$data = Stream::get_now_playing();
- $r = Subsonic_XML_Data::createSuccessResponse();
+ $r = Subsonic_XML_Data::createSuccessResponse();
Subsonic_XML_Data::addNowPlaying($r, $data);
self::apiOutput($input, $r);
}
@@ -696,44 +755,56 @@ class Subsonic_Api
$operator = 0;
if (strlen($query) > 1) {
if (substr($query, -1) == "*") {
- $query = substr($query, 0, -1);
+ $query = substr($query, 0, -1);
$operator = 2; // Start with
}
}
- $artistCount = $input['artistCount'];
+ $artistCount = isset($input['artistCount']) ? $input['artistCount'] : 20;
$artistOffset = $input['artistOffset'];
- $albumCount = $input['albumCount'];
- $albumOffset = $input['albumOffset'];
- $songCount = $input['songCount'];
- $songOffset = $input['songOffset'];
+ $albumCount = isset($input['albumCount']) ? $input['albumCount'] : 20;
+ $albumOffset = $input['albumOffset'];
+ $songCount = isset($input['songCount']) ? $input['songCount'] : 20;
+ $songOffset = $input['songOffset'];
- $sartist = array();
+ $sartist = array();
$sartist['limit'] = $artistCount;
- if ($artistOffset) $sartist['offset'] = $artistOffset;
- $sartist['rule_1_input'] = $query;
+ if ($artistOffset) {
+ $sartist['offset'] = $artistOffset;
+ }
+ $sartist['rule_1_input'] = $query;
$sartist['rule_1_operator'] = $operator;
- $sartist['rule_1'] = "name";
- $sartist['type'] = "artist";
- $artists = Search::run($sartist);
+ $sartist['rule_1'] = "name";
+ $sartist['type'] = "artist";
+ if ($artistCount > 0) {
+ $artists = Search::run($sartist);
+ }
- $salbum = array();
+ $salbum = array();
$salbum['limit'] = $albumCount;
- if ($albumOffset) $salbum['offset'] = $albumOffset;
- $salbum['rule_1_input'] = $query;
+ if ($albumOffset) {
+ $salbum['offset'] = $albumOffset;
+ }
+ $salbum['rule_1_input'] = $query;
$salbum['rule_1_operator'] = $operator;
- $salbum['rule_1'] = "title";
- $salbum['type'] = "album";
- $albums = Search::run($salbum);
+ $salbum['rule_1'] = "title";
+ $salbum['type'] = "album";
+ if ($albumCount > 0) {
+ $albums = Search::run($salbum);
+ }
- $ssong = array();
+ $ssong = array();
$ssong['limit'] = $songCount;
- if ($songOffset) $ssong['offset'] = $songOffset;
- $ssong['rule_1_input'] = $query;
+ if ($songOffset) {
+ $ssong['offset'] = $songOffset;
+ }
+ $ssong['rule_1_input'] = $query;
$ssong['rule_1_operator'] = $operator;
- $ssong['rule_1'] = "anywhere";
- $ssong['type'] = "song";
- $songs = Search::run($ssong);
+ $ssong['rule_1'] = "anywhere";
+ $ssong['type'] = "song";
+ if ($songCount > 0) {
+ $songs = Search::run($ssong);
+ }
$r = Subsonic_XML_Data::createSuccessResponse();
Subsonic_XML_Data::addSearchResult($r, $artists, $albums, $songs, $elementName);
@@ -759,7 +830,7 @@ class Subsonic_Api
{
self::check_version($input);
- $r = Subsonic_XML_Data::createSuccessResponse();
+ $r = Subsonic_XML_Data::createSuccessResponse();
$username = $input['username'];
// Don't allow playlist listing for another user
@@ -808,20 +879,22 @@ class Subsonic_Api
self::check_version($input, "1.2.0");
$playlistId = $input['playlistId'];
- $name = $input['name'];
- $songId = $input['songId'];
+ $name = $input['name'];
+ $songId = $input['songId'];
if ($playlistId) {
self::_updatePlaylist($playlistId, $name, $songId);
$r = Subsonic_XML_Data::createSuccessResponse();
- } else if (!empty($name)) {
- $playlistId = Playlist::create($name, 'private');
- if (count($songId) > 0) {
- self::_updatePlaylist($playlistId, "", $songId);
- }
- $r = Subsonic_XML_Data::createSuccessResponse();
} else {
- $r = Subsonic_XML_Data::createError(Subsonic_XML_Data::SSERROR_MISSINGPARAM);
+ if (!empty($name)) {
+ $playlistId = Playlist::create($name, 'private');
+ if (count($songId) > 0) {
+ self::_updatePlaylist($playlistId, "", $songId);
+ }
+ $r = Subsonic_XML_Data::createSuccessResponse();
+ } else {
+ $r = Subsonic_XML_Data::createError(Subsonic_XML_Data::SSERROR_MISSINGPARAM);
+ }
}
self::apiOutput($input, $r);
}
@@ -830,8 +903,8 @@ class Subsonic_Api
{
$playlist = new Playlist($id);
- $newdata = array();
- $newdata['name'] = (!empty($name)) ? $name : $playlist->name;
+ $newdata = array();
+ $newdata['name'] = (!empty($name)) ? $name : $playlist->name;
$newdata['pl_type'] = ($public) ? "public" : "private";
$playlist->update($newdata);
@@ -871,12 +944,12 @@ class Subsonic_Api
$playlistId = self::check_parameter($input, 'playlistId');
- $name = $input['name'];
+ $name = $input['name'];
$comment = $input['comment']; // Not supported.
- $public = ($input['public'] === "true");
+ $public = ($input['public'] === "true");
if (!Subsonic_XML_Data::isSmartPlaylist($playlistId)) {
- $songIdToAdd = $input['songIdToAdd'];
+ $songIdToAdd = $input['songIdToAdd'];
$songIndexToRemove = $input['songIndexToRemove'];
self::_updatePlaylist(Subsonic_XML_Data::getAmpacheId($playlistId), $name, $songIdToAdd, $songIndexToRemove, $public);
@@ -922,10 +995,10 @@ class Subsonic_Api
$fileid = self::check_parameter($input, 'id', true);
- $maxBitRate = $input['maxBitRate'];
- $format = $input['format']; // mp3, flv or raw
- $timeOffset = $input['timeOffset'];
- $size = $input['size']; // For video streaming. Not supported.
+ $maxBitRate = $input['maxBitRate'];
+ $format = $input['format']; // mp3, flv or raw
+ $timeOffset = $input['timeOffset'];
+ $size = $input['size']; // For video streaming. Not supported.
$estimateContentLength = $input['estimateContentLength']; // Force content-length guessing if transcode
$params = '&client=' . rawurlencode($input['c']) . '&noscrobble=1';
@@ -945,8 +1018,10 @@ class Subsonic_Api
$url = '';
if (Subsonic_XML_Data::isVideo($fileid)) {
$url = Video::play_url(Subsonic_XML_Data::getAmpacheId($fileid), $params, 'api', function_exists('curl_version'));
- } else if (Subsonic_XML_Data::isSong($fileid)) {
+ } elseif (Subsonic_XML_Data::isSong($fileid)) {
$url = Song::play_url(Subsonic_XML_Data::getAmpacheId($fileid), $params, 'api', function_exists('curl_version'));
+ } elseif (Subsonic_XML_Data::isPodcastEp($fileid)) {
+ $url = Podcast_Episode::play_url(Subsonic_XML_Data::getAmpacheId($fileid), $params, 'api', function_exists('curl_version'));
}
if (!empty($url)) {
@@ -982,13 +1057,13 @@ class Subsonic_Api
$bitRate = $input['bitRate'];
- $media = array();
+ $media = array();
$media['object_type'] = 'song';
- $media['object_id'] = Subsonic_XML_Data::getAmpacheId($fileid);
+ $media['object_id'] = Subsonic_XML_Data::getAmpacheId($fileid);
- $medias = array();
- $medias[] = $media;
- $stream = new Stream_Playlist();
+ $medias = array();
+ $medias[] = $media;
+ $stream = new Stream_Playlist();
$additional_params = '';
if ($bitRate) {
$additional_params .= '&bitrate=' . $bitRate;
@@ -1009,25 +1084,34 @@ class Subsonic_Api
{
self::check_version($input, "1.0.0", true);
- $id = self::check_parameter($input, 'id', true);
+ $id = self::check_parameter($input, 'id', true);
$size = $input['size'];
$art = null;
if (Subsonic_XML_Data::isArtist($id)) {
$art = new Art(Subsonic_XML_Data::getAmpacheId($id), "artist");
- } else if (Subsonic_XML_Data::isAlbum($id)) {
+ } elseif (Subsonic_XML_Data::isAlbum($id)) {
$art = new Art(Subsonic_XML_Data::getAmpacheId($id), "album");
- } else if (Subsonic_XML_Data::isSong($id)) {
+ } elseif (Subsonic_XML_Data::isSong($id)) {
$art = new Art(Subsonic_XML_Data::getAmpacheId($id), "song");
+ if ($art != null && $art->id == null) {
+ // in most cases the song doesn't have a picture, but the album where it belongs to has
+ // if this is the case, we take the album art
+ $song = new Song(Subsonic_XML_Data::getAmpacheId(Subsonic_XML_Data::getAmpacheId($id)));
+ $art = new Art(Subsonic_XML_Data::getAmpacheId($song->album), "album");
+ }
+ } elseif (Subsonic_XML_Data::isPodcast($id)) {
+ $art = new Art(Subsonic_XML_Data::getAmpacheId($id), "podcast");
}
+ header("Access-Control-Allow-Origin: *");
if ($art != null) {
$art->get_db();
- if ($size) {
- $dim = array();
- $dim['width'] = $size;
+ if ($size && AmpConfig::get('resize_images')) {
+ $dim = array();
+ $dim['width'] = $size;
$dim['height'] = $size;
- $thumb = $art->get_thumb($dim);
+ $thumb = $art->get_thumb($dim);
if ($thumb) {
header('Content-type: ' . $thumb['thumb_mime']);
header('Content-Length: ' . strlen($thumb['thumb']));
@@ -1051,16 +1135,20 @@ class Subsonic_Api
{
self::check_version($input, "1.6.0");
- $id = self::check_parameter($input, 'id');
+ $id = self::check_parameter($input, 'id');
$rating = $input['rating'];
$robj = null;
if (Subsonic_XML_Data::isArtist($id)) {
$robj = new Rating(Subsonic_XML_Data::getAmpacheId($id), "artist");
- } else if (Subsonic_XML_Data::isAlbum($id)) {
- $robj = new Rating(Subsonic_XML_Data::getAmpacheId($id), "album");
- } else if (Subsonic_XML_Data::isSong($id)) {
- $robj = new Rating(Subsonic_XML_Data::getAmpacheId($id), "song");
+ } else {
+ if (Subsonic_XML_Data::isAlbum($id)) {
+ $robj = new Rating(Subsonic_XML_Data::getAmpacheId($id), "album");
+ } else {
+ if (Subsonic_XML_Data::isSong($id)) {
+ $robj = new Rating(Subsonic_XML_Data::getAmpacheId($id), "song");
+ }
+ }
}
if ($robj != null) {
@@ -1085,7 +1173,7 @@ class Subsonic_Api
self::check_version($input, "1.7.0");
$r = Subsonic_XML_Data::createSuccessResponse();
- Subsonic_XML_Data::addStarred($r, Userflag::get_latest('artist'), Userflag::get_latest('album'), Userflag::get_latest('song'), $elementName);
+ Subsonic_XML_Data::addStarred($r, Userflag::get_latest('artist',null,99999), Userflag::get_latest('album',null,99999), Userflag::get_latest('song',null,99999), $elementName);
self::apiOutput($input, $r);
}
@@ -1127,8 +1215,8 @@ class Subsonic_Api
private static function _setStar($input, $star)
{
- $id = $input['id'];
- $albumId = $input['albumId'];
+ $id = $input['id'];
+ $albumId = $input['albumId'];
$artistId = $input['artistId'];
// Normalize all in one array
@@ -1143,36 +1231,44 @@ class Subsonic_Api
$aid = Subsonic_XML_Data::getAmpacheId($i);
if (Subsonic_XML_Data::isArtist($i)) {
$type = 'artist';
- } else if (Subsonic_XML_Data::isAlbum($i)) {
- $type = 'album';
- } else if (Subsonic_XML_Data::isSong($i)) {
- $type = 'song';
} else {
- $type = "";
+ if (Subsonic_XML_Data::isAlbum($i)) {
+ $type = 'album';
+ } else {
+ if (Subsonic_XML_Data::isSong($i)) {
+ $type = 'song';
+ } else {
+ $type = "";
+ }
+ }
}
$ids[] = array('id' => $aid, 'type' => $type);
}
- } else if ($albumId) {
- if (!is_array($albumId)) {
- $albumId = array($albumId);
- }
- foreach ($albumId as $i) {
- $aid = Subsonic_XML_Data::getAmpacheId($i);
- $ids[] = array('id' => $aid, 'album');
- }
- } else if ($artistId) {
- if (!is_array($artistId)) {
- $artistId = array($artistId);
- }
- foreach ($artistId as $i) {
- $aid = Subsonic_XML_Data::getAmpacheId($i);
- $ids[] = array('id' => $aid, 'artist');
- }
} else {
- $r = Subsonic_XML_Data::createError(Subsonic_XML_Data::SSERROR_MISSINGPARAM);
+ if ($albumId) {
+ if (!is_array($albumId)) {
+ $albumId = array($albumId);
+ }
+ foreach ($albumId as $i) {
+ $aid = Subsonic_XML_Data::getAmpacheId($i);
+ $ids[] = array('id' => $aid, 'album');
+ }
+ } else {
+ if ($artistId) {
+ if (!is_array($artistId)) {
+ $artistId = array($artistId);
+ }
+ foreach ($artistId as $i) {
+ $aid = Subsonic_XML_Data::getAmpacheId($i);
+ $ids[] = array('id' => $aid, 'artist');
+ }
+ } else {
+ $r = Subsonic_XML_Data::createError(Subsonic_XML_Data::SSERROR_MISSINGPARAM);
+ }
+ }
}
- foreach ($ids as $i) {
+ foreach ($ids as $i) {
$flag = new Userflag($i['id'], $i['type']);
$flag->set_flag($star);
}
@@ -1216,7 +1312,7 @@ class Subsonic_Api
self::check_version($input, "1.7.0");
if ($GLOBALS['user']->access >= 100) {
- $r = Subsonic_XML_Data::createSuccessResponse();
+ $r = Subsonic_XML_Data::createSuccessResponse();
$users = User::get_valid_users();
Subsonic_XML_Data::addUsers($r, $users);
} else {
@@ -1269,7 +1365,7 @@ class Subsonic_Api
{
self::check_version($input, "1.9.0");
- $r = Subsonic_XML_Data::createSuccessResponse();
+ $r = Subsonic_XML_Data::createSuccessResponse();
$radios = Live_Stream::get_all_radios();
Subsonic_XML_Data::addRadios($r, $radios);
self::apiOutput($input, $r);
@@ -1284,7 +1380,7 @@ class Subsonic_Api
{
self::check_version($input, "1.6.0");
- $r = Subsonic_XML_Data::createSuccessResponse();
+ $r = Subsonic_XML_Data::createSuccessResponse();
$shares = Share::get_share_list();
Subsonic_XML_Data::addShares($r, $shares);
self::apiOutput($input, $r);
@@ -1299,7 +1395,7 @@ class Subsonic_Api
{
self::check_version($input, "1.6.0");
- $id = self::check_parameter($input, 'id');
+ $id = self::check_parameter($input, 'id');
$description = $input['description'];
if (AmpConfig::get('share')) {
@@ -1317,13 +1413,15 @@ class Subsonic_Api
$object_id = Subsonic_XML_Data::getAmpacheId($id);
if (Subsonic_XML_Data::isAlbum($id)) {
$object_type = 'album';
- } else if (Subsonic_XML_Data::isSong($id)) {
- $object_type = 'song';
+ } else {
+ if (Subsonic_XML_Data::isSong($id)) {
+ $object_type = 'song';
+ }
}
if (!empty($object_type)) {
- $r = Subsonic_XML_Data::createSuccessResponse();
- $shares = array();
+ $r = Subsonic_XML_Data::createSuccessResponse();
+ $shares = array();
$shares[] = Share::create_share($object_type, $object_id, true, Access::check_function('download'), $expire_days, Share::generate_secret(), 0, $description);
Subsonic_XML_Data::addShares($r, $shares);
} else {
@@ -1368,7 +1466,7 @@ class Subsonic_Api
{
self::check_version($input, "1.6.0");
- $id = self::check_parameter($input, 'id');
+ $id = self::check_parameter($input, 'id');
$description = $input['description'];
if (AmpConfig::get('share')) {
@@ -1418,16 +1516,16 @@ class Subsonic_Api
{
self::check_version($input, "1.1.0");
- $username = self::check_parameter($input, 'username');
- $password = self::check_parameter($input, 'password');
- $email = self::check_parameter($input, 'email');
+ $username = self::check_parameter($input, 'username');
+ $password = self::check_parameter($input, 'password');
+ $email = self::check_parameter($input, 'email');
$ldapAuthenticated = $input['ldapAuthenticated'];
- $adminRole = ($input['adminRole'] == 'true');
+ $adminRole = ($input['adminRole'] == 'true');
//$settingsRole = $input['settingsRole'];
//$streamRole = $input['streamRole'];
//$jukeboxRole = $input['jukeboxRole'];
$downloadRole = ($input['downloadRole'] == 'true');
- $uploadRole = ($input['uploadRole'] == 'true');
+ $uploadRole = ($input['uploadRole'] == 'true');
//$playlistRole = $input['playlistRole'];
$coverArtRole = ($input['coverArtRole'] == 'true');
//$commentRole = $input['commentRole'];
@@ -1442,7 +1540,7 @@ class Subsonic_Api
$access = 75;
}
$password = self::decrypt_password($password);
- $user_id = User::create($username, $username, $email, null, $password, $access);
+ $user_id = User::create($username, $username, $email, null, $password, $access);
if ($user_id > 0) {
if ($downloadRole) {
Preference::update('download', $user_id, '1');
@@ -1526,8 +1624,8 @@ class Subsonic_Api
{
self::check_version($input, "1.2.0");
$action = self::check_parameter($input, 'action');
- $id = $input['id'];
- $gain = $input['gain'];
+ $id = $input['id'];
+ $gain = $input['gain'];
$r = Subsonic_XML_Data::createError(Subsonic_XML_Data::SSERROR_DATA_NOTFOUND);
debug_event('subsonic', 'Using Localplay controller: ' . AmpConfig::get('localplay_controller'), 5);
@@ -1548,8 +1646,9 @@ class Subsonic_Api
break;
case 'skip':
if (isset($input['index'])) {
- if ($localplay->skip($input['index']))
+ if ($localplay->skip($input['index'])) {
$ret = $localplay->play();
+ }
} elseif (isset($input['offset'])) {
debug_event('subsonic', 'Skip with offset is not supported on JukeboxControl.', 5);
} else {
@@ -1561,9 +1660,9 @@ class Subsonic_Api
case 'add':
if ($id) {
if (!is_array($id)) {
- $rid = array();
+ $rid = array();
$rid[] = $id;
- $id = $rid;
+ $id = $rid;
}
foreach ($id as $i) {
@@ -1576,9 +1675,9 @@ class Subsonic_Api
if ($url) {
debug_event('subsonic', 'Adding ' . $url, 5);
- $stream = array();
+ $stream = array();
$stream['url'] = $url;
- $ret = $localplay->add_url(new Stream_URL($stream));
+ $ret = $localplay->add_url(new Stream_URL($stream));
}
}
}
@@ -1628,9 +1727,9 @@ class Subsonic_Api
//$submission = $input['submission'];
if (!is_array($id)) {
- $rid = array();
+ $rid = array();
$rid[] = $id;
- $id = $rid;
+ $id = $rid;
}
foreach ($id as $i) {
@@ -1660,27 +1759,27 @@ class Subsonic_Api
self::check_version($input, "1.2.0");
$artist = $input['artist'];
- $title = $input['title'];
+ $title = $input['title'];
if (!$artist && !$title) {
$r = Subsonic_XML_Data::createError(Subsonic_XML_Data::SSERROR_MISSINGPARAM);
} else {
- $search = array();
- $search['limit'] = 1;
+ $search = array();
+ $search['limit'] = 1;
$search['offset'] = 0;
- $search['type'] = "song";
+ $search['type'] = "song";
$i = 0;
if ($artist) {
- $search['rule_'.$i.'_input'] = $artist;
- $search['rule_'.$i.'_operator'] = 5;
- $search['rule_'.$i.''] = "artist";
+ $search['rule_' . $i . '_input'] = $artist;
+ $search['rule_' . $i . '_operator'] = 5;
+ $search['rule_' . $i . ''] = "artist";
++$i;
}
if ($title) {
- $search['rule_'.$i.'_input'] = $title;
- $search['rule_'.$i.'_operator'] = 5;
- $search['rule_'.$i.''] = "title";
+ $search['rule_' . $i . '_input'] = $title;
+ $search['rule_' . $i . '_operator'] = 5;
+ $search['rule_' . $i . ''] = "title";
++$i;
}
@@ -1703,15 +1802,15 @@ class Subsonic_Api
*/
public static function getartistinfo($input)
{
- $id = self::check_parameter($input, 'id');
- $count = $input['count'] ?: 20;
+ $id = self::check_parameter($input, 'id');
+ $count = $input['count'] ?: 20;
$includeNotPresent = ($input['includeNotPresent'] === "true");
if (Subsonic_XML_Data::isArtist($id)) {
$artist_id = Subsonic_XML_Data::getAmpacheId($id);
- $info = Recommendation::get_artist_info($artist_id);
- $similars = Recommendation::get_artists_like($artist_id, $count, !$includeNotPresent);
- $r = Subsonic_XML_Data::createSuccessResponse();
+ $info = Recommendation::get_artist_info($artist_id);
+ $similars = Recommendation::get_artists_like($artist_id, $count, !$includeNotPresent);
+ $r = Subsonic_XML_Data::createSuccessResponse();
Subsonic_XML_Data::addArtistInfo($r, $info, $similars);
} else {
$r = Subsonic_XML_Data::createError(Subsonic_XML_Data::SSERROR_DATA_NOTFOUND);
@@ -1736,7 +1835,7 @@ class Subsonic_Api
*/
public static function getsimilarsongs($input)
{
- $id = self::check_parameter($input, 'id');
+ $id = self::check_parameter($input, 'id');
$count = $input['count'] ?: 50;
$songs = null;
@@ -1769,19 +1868,54 @@ class Subsonic_Api
return self::getsimilarsongs($input);
}
- /**** CURRENT UNSUPPORTED FUNCTIONS ****/
-
/**
* getPodcasts
* Get all podcast channels.
* Takes the optional includeEpisodes and channel id in parameters
- * Not supported.
*/
public static function getpodcasts($input)
{
self::check_version($input, "1.6.0");
+ $id = $input['id'];
+ $includeEpisodes = isset($input['includeEpisodes']) ? $input['includeEpisodes'] : true;
- $r = Subsonic_XML_Data::createError(Subsonic_XML_Data::SSERROR_DATA_NOTFOUND);
+ if (AmpConfig::get('podcast')) {
+ if ($id) {
+ $podcast = new Podcast(Subsonic_XML_Data::getAmpacheId($id));
+ if ($podcast->id) {
+ $r = Subsonic_XML_Data::createSuccessResponse();
+ Subsonic_XML_Data::addPodcasts($r, array($podcast), $includeEpisodes);
+ } else {
+ $r = Subsonic_XML_Data::createError(Subsonic_XML_Data::SSERROR_DATA_NOTFOUND);
+ }
+ } else {
+ $podcasts = Catalog::get_podcasts();
+ $r = Subsonic_XML_Data::createSuccessResponse();
+ Subsonic_XML_Data::addPodcasts($r, $podcasts, $includeEpisodes);
+ }
+ } else {
+ $r = Subsonic_XML_Data::createError(Subsonic_XML_Data::SSERROR_UNAUTHORIZED);
+ }
+ self::apiOutput($input, $r);
+ }
+
+ /**
+ * getNewestPodcasts
+ * Get the most recently published podcast episodes.
+ * Takes the optional count in parameters
+ */
+ public static function getnewestpodcasts($input)
+ {
+ self::check_version($input, "1.13.0");
+ $count = $input['count'] ?: 20;
+
+ if (AmpConfig::get('podcast')) {
+ $r = Subsonic_XML_Data::createSuccessResponse();
+ $episodes = Catalog::get_newest_podcasts($count);
+ Subsonic_XML_Data::addNewestPodcastEpisodes($r, $episodes);
+ } else {
+ $r = Subsonic_XML_Data::createError(Subsonic_XML_Data::SSERROR_UNAUTHORIZED);
+ }
self::apiOutput($input, $r);
}
@@ -1789,13 +1923,20 @@ class Subsonic_Api
* refreshPodcasts
* Request the server to check for new podcast episodes.
* Takes no parameters.
- * Not supported.
*/
public static function refreshpodcasts($input)
{
self::check_version($input, "1.9.0");
- $r = Subsonic_XML_Data::createError(Subsonic_XML_Data::SSERROR_DATA_NOTFOUND);
+ if (AmpConfig::get('podcast') && Access::check('interface', 75)) {
+ $podcasts = Catalog::get_podcasts();
+ foreach ($podcasts as $podcast) {
+ $podcast->sync_episodes(true);
+ }
+ $r = Subsonic_XML_Data::createSuccessResponse();
+ } else {
+ $r = Subsonic_XML_Data::createError(Subsonic_XML_Data::SSERROR_UNAUTHORIZED);
+ }
self::apiOutput($input, $r);
}
@@ -1803,13 +1944,29 @@ class Subsonic_Api
* createPodcastChannel
* Add a new podcast channel.
* Takes the podcast url in parameter.
- * Not supported.
*/
public static function createpodcastchannel($input)
{
self::check_version($input, "1.9.0");
-
- $r = Subsonic_XML_Data::createError(Subsonic_XML_Data::SSERROR_DATA_NOTFOUND);
+ $url = self::check_parameter($input, 'url');
+
+ if (AmpConfig::get('podcast') && Access::check('interface', 75)) {
+ $catalogs = Catalog::get_catalogs('podcast');
+ if (count($catalogs) > 0) {
+ $data = array();
+ $data['feed'] = $url;
+ $data['catalog'] = $catalogs[0];
+ if (Podcast::create($data)) {
+ $r = Subsonic_XML_Data::createSuccessResponse();
+ } else {
+ $r = Subsonic_XML_Data::createError(Subsonic_XML_Data::SSERROR_GENERIC);
+ }
+ } else {
+ $r = Subsonic_XML_Data::createError(Subsonic_XML_Data::SSERROR_UNAUTHORIZED);
+ }
+ } else {
+ $r = Subsonic_XML_Data::createError(Subsonic_XML_Data::SSERROR_UNAUTHORIZED);
+ }
self::apiOutput($input, $r);
}
@@ -1817,13 +1974,26 @@ class Subsonic_Api
* deletePodcastChannel
* Delete an existing podcast channel
* Takes the podcast id in parameter.
- * Not supported.
*/
public static function deletepodcastchannel($input)
{
self::check_version($input, "1.9.0");
-
- $r = Subsonic_XML_Data::createError(Subsonic_XML_Data::SSERROR_DATA_NOTFOUND);
+ $id = self::check_parameter($input, 'id');
+
+ if (AmpConfig::get('podcast') && Access::check('interface', 75)) {
+ $podcast = new Podcast(Subsonic_XML_Data::getAmpacheId($id));
+ if ($podcast->id) {
+ if ($podcast->remove()) {
+ $r = Subsonic_XML_Data::createSuccessResponse();
+ } else {
+ $r = Subsonic_XML_Data::createError(Subsonic_XML_Data::SSERROR_GENERIC);
+ }
+ } else {
+ $r = Subsonic_XML_Data::createError(Subsonic_XML_Data::SSERROR_DATA_NOTFOUND);
+ }
+ } else {
+ $r = Subsonic_XML_Data::createError(Subsonic_XML_Data::SSERROR_UNAUTHORIZED);
+ }
self::apiOutput($input, $r);
}
@@ -1831,13 +2001,26 @@ class Subsonic_Api
* deletePodcastEpisode
* Delete a podcast episode
* Takes the podcast episode id in parameter.
- * Not supported.
*/
public static function deletepodcastepisode($input)
{
self::check_version($input, "1.9.0");
-
- $r = Subsonic_XML_Data::createError(Subsonic_XML_Data::SSERROR_DATA_NOTFOUND);
+ $id = self::check_parameter($input, 'id');
+
+ if (AmpConfig::get('podcast') && Access::check('interface', 75)) {
+ $episode = new Podcast_Episode(Subsonic_XML_Data::getAmpacheId($id));
+ if ($episode->id) {
+ if ($episode->remove()) {
+ $r = Subsonic_XML_Data::createSuccessResponse();
+ } else {
+ $r = Subsonic_XML_Data::createError(Subsonic_XML_Data::SSERROR_GENERIC);
+ }
+ } else {
+ $r = Subsonic_XML_Data::createError(Subsonic_XML_Data::SSERROR_DATA_NOTFOUND);
+ }
+ } else {
+ $r = Subsonic_XML_Data::createError(Subsonic_XML_Data::SSERROR_UNAUTHORIZED);
+ }
self::apiOutput($input, $r);
}
@@ -1845,15 +2028,98 @@ class Subsonic_Api
* downloadPodcastEpisode
* Request the server to download a podcast episode
* Takes the podcast episode id in parameter.
- * Not supported.
*/
public static function downloadpodcastepisode($input)
{
self::check_version($input, "1.9.0");
-
- $r = Subsonic_XML_Data::createError(Subsonic_XML_Data::SSERROR_DATA_NOTFOUND);
+ $id = self::check_parameter($input, 'id');
+
+ if (AmpConfig::get('podcast') && Access::check('interface', 75)) {
+ $episode = new Podcast_Episode(Subsonic_XML_Data::getAmpacheId($id));
+ if ($episode->id) {
+ $episode->gather();
+ $r = Subsonic_XML_Data::createSuccessResponse();
+ } else {
+ $r = Subsonic_XML_Data::createError(Subsonic_XML_Data::SSERROR_DATA_NOTFOUND);
+ }
+ } else {
+ $r = Subsonic_XML_Data::createError(Subsonic_XML_Data::SSERROR_UNAUTHORIZED);
+ }
self::apiOutput($input, $r);
}
+
+ /**
+ * getBookmarks
+ * Get all user bookmarks.
+ * Takes no parameter.
+ * Not supported.
+ */
+ public static function getbookmarks($input)
+ {
+ self::check_version($input, "1.9.0");
+
+ $r = Subsonic_XML_Data::createSuccessResponse();
+ $bookmarks = Bookmark::get_bookmarks();
+ Subsonic_XML_Data::addBookmarks($r, $bookmarks);
+ self::apiOutput($input, $r);
+ }
+
+ /**
+ * createBookmark
+ * Creates or updates a bookmark.
+ * Takes the file id and position with optional comment in parameters.
+ * Not supported.
+ */
+ public static function createbookmark($input)
+ {
+ self::check_version($input, "1.9.0");
+ $id = self::check_parameter($input, 'id');
+ $position = self::check_parameter($input, 'position');
+ $comment = $input['comment'];
+ $type = Subsonic_XML_Data::getAmpacheType($id);
+
+ if (!empty($type)) {
+ $bookmark = new Bookmark(Subsonic_XML_Data::getAmpacheId($id), $type);
+ if ($bookmark->id) {
+ $bookmark->update($position);
+ } else {
+ Bookmark::create(array(
+ 'object_id' => Subsonic_XML_Data::getAmpacheId($id),
+ 'object_type' => $type,
+ 'comment' => $comment,
+ 'position' => $position
+ ));
+ }
+ $r = Subsonic_XML_Data::createSuccessResponse();
+ } else {
+ $r = Subsonic_XML_Data::createError(Subsonic_XML_Data::SSERROR_DATA_NOTFOUND);
+ }
+ self::apiOutput($input, $r);
+ }
+
+ /**
+ * deleteBookmark
+ * Delete an existing bookmark.
+ * Takes the file id in parameter.
+ * Not supported.
+ */
+ public static function deletebookmark($input)
+ {
+ self::check_version($input, "1.9.0");
+ $id = self::check_parameter($input, 'id');
+ $type = Subsonic_XML_Data::getAmpacheType($id);
+
+ $bookmark = new Bookmark(Subsonic_XML_Data::getAmpacheId($id), $type);
+ if ($bookmark->id) {
+ $bookmark->remove();
+ $r = Subsonic_XML_Data::createSuccessResponse();
+ } else {
+ $r = Subsonic_XML_Data::createError(Subsonic_XML_Data::SSERROR_DATA_NOTFOUND);
+ }
+ self::apiOutput($input, $r);
+ }
+
+ /**** CURRENT UNSUPPORTED FUNCTIONS ****/
/**
* getChatMessages
@@ -1882,44 +2148,30 @@ class Subsonic_Api
$r = Subsonic_XML_Data::createError(Subsonic_XML_Data::SSERROR_DATA_NOTFOUND);
self::apiOutput($input, $r);
}
-
+
/**
- * getBookmarks
- * Get all user bookmarks.
+ * getPlayQueue
+ * Geturns the state of the play queue for the authenticated user.
* Takes no parameter.
* Not supported.
*/
- public static function getbookmarks($input)
+ public static function getplayqueue($input)
{
- self::check_version($input, "1.9.0");
+ self::check_version($input, "1.12.0");
$r = Subsonic_XML_Data::createError(Subsonic_XML_Data::SSERROR_DATA_NOTFOUND);
self::apiOutput($input, $r);
}
-
+
/**
- * createBookmark
- * Creates or updates a bookmark.
- * Takes the file id and position with optional comment in parameters.
+ * savePlayQueue
+ * Save the state of the play queue for the authenticated user.
+ * Takes multiple song id in parameter with optional current id playing sond and position.
* Not supported.
*/
- public static function createbookmark($input)
+ public static function saveplayqueue($input)
{
- self::check_version($input, "1.9.0");
-
- $r = Subsonic_XML_Data::createError(Subsonic_XML_Data::SSERROR_DATA_NOTFOUND);
- self::apiOutput($input, $r);
- }
-
- /**
- * deleteBookmark
- * Delete an existing bookmark.
- * Takes the file id in parameter.
- * Not supported.
- */
- public static function deletebookmark($input)
- {
- self::check_version($input, "1.9.0");
+ self::check_version($input, "1.12.0");
$r = Subsonic_XML_Data::createError(Subsonic_XML_Data::SSERROR_DATA_NOTFOUND);
self::apiOutput($input, $r);
diff --git a/sources/lib/class/subsonic_xml_data.class.php b/sources/lib/class/subsonic_xml_data.class.php
index 675b8fd..ffca28d 100644
--- a/sources/lib/class/subsonic_xml_data.class.php
+++ b/sources/lib/class/subsonic_xml_data.class.php
@@ -2,22 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; version 2
- * of the License.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -32,21 +31,25 @@ class Subsonic_XML_Data
{
const API_VERSION = "1.11.0";
- const SSERROR_GENERIC = 0;
- const SSERROR_MISSINGPARAM = 10;
+ const SSERROR_GENERIC = 0;
+ const SSERROR_MISSINGPARAM = 10;
const SSERROR_APIVERSION_CLIENT = 20;
const SSERROR_APIVERSION_SERVER = 30;
- const SSERROR_BADAUTH = 40;
- const SSERROR_UNAUTHORIZED = 50;
- const SSERROR_TRIAL = 60;
- const SSERROR_DATA_NOTFOUND = 70;
+ const SSERROR_BADAUTH = 40;
+ const SSERROR_UNAUTHORIZED = 50;
+ const SSERROR_TRIAL = 60;
+ 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.
- const AMPACHEID_ARTIST = 100000000;
- const AMPACHEID_ALBUM = 200000000;
- const AMPACHEID_SONG = 300000000;
- const AMPACHEID_SMARTPL = 400000000;
- const AMPACHEID_VIDEO = 500000000;
+ const AMPACHEID_ARTIST = 100000000;
+ const AMPACHEID_ALBUM = 200000000;
+ const AMPACHEID_SONG = 300000000;
+ const AMPACHEID_SMARTPL = 400000000;
+ const AMPACHEID_VIDEO = 500000000;
+ const AMPACHEID_PODCAST = 600000000;
+ const AMPACHEID_PODCASTEP = 700000000;
+
+ public static $enable_json_checks = false;
/**
* constructor
@@ -81,10 +84,30 @@ class Subsonic_XML_Data
{
return $id + Subsonic_XML_Data::AMPACHEID_VIDEO;
}
+
+ public static function getPodcastId($id)
+ {
+ return $id + Subsonic_XML_Data::AMPACHEID_PODCAST;
+ }
+
+ public static function getPodcastEpId($id)
+ {
+ return $id + Subsonic_XML_Data::AMPACHEID_PODCASTEP;
+ }
+
+ private static function cleanId($id)
+ {
+ // Remove all al-, ar-, ... prefixs
+ $tpos = strpos($id, "-");
+ if ($tpos !== false) {
+ $id = intval(substr($id, $tpos + 1));
+ }
+ return $id;
+ }
public static function getAmpacheId($id)
{
- return ($id % Subsonic_XML_Data::AMPACHEID_ARTIST);
+ return (self::cleanId($id) % Subsonic_XML_Data::AMPACHEID_ARTIST);
}
public static function getAmpacheIds($ids)
@@ -98,27 +121,65 @@ class Subsonic_XML_Data
public static function isArtist($id)
{
+ $id = self::cleanId($id);
return ($id >= Subsonic_XML_Data::AMPACHEID_ARTIST && $id < Subsonic_XML_Data::AMPACHEID_ALBUM);
}
public static function isAlbum($id)
{
+ $id = self::cleanId($id);
return ($id >= Subsonic_XML_Data::AMPACHEID_ALBUM && $id < Subsonic_XML_Data::AMPACHEID_SONG);
}
public static function isSong($id)
{
- return ($id >= Subsonic_XML_Data::AMPACHEID_SONG);
+ $id = self::cleanId($id);
+ return ($id >= Subsonic_XML_Data::AMPACHEID_SONG && $id < Subsonic_XML_Data::AMPACHEID_SMARTPL);
}
public static function isSmartPlaylist($id)
{
- return ($id >= Subsonic_XML_Data::AMPACHEID_SMARTPL);
+ $id = self::cleanId($id);
+ return ($id >= Subsonic_XML_Data::AMPACHEID_SMARTPL && $id < Subsonic_XML_Data::AMPACHEID_VIDEO);
}
public static function isVideo($id)
{
- return ($id >= Subsonic_XML_Data::AMPACHEID_VIDEO);
+ $id = self::cleanId($id);
+ return ($id >= Subsonic_XML_Data::AMPACHEID_VIDEO && $id < Subsonic_XML_Data::AMPACHEID_PODCAST);
+ }
+
+ public static function isPodcast($id)
+ {
+ $id = self::cleanId($id);
+ return ($id >= Subsonic_XML_Data::AMPACHEID_PODCAST && $id < Subsonic_XML_Data::AMPACHEID_PODCASTEP);
+ }
+
+ public static function isPodcastEp($id)
+ {
+ $id = self::cleanId($id);
+ return ($id >= Subsonic_XML_Data::AMPACHEID_PODCASTEP);
+ }
+
+ public static function getAmpacheType($id)
+ {
+ if (self::isArtist($id)) {
+ return "artist";
+ } elseif (self::isAlbum($id)) {
+ return "album";
+ } elseif (self::isSong($id)) {
+ return "song";
+ } elseif (self::isSmartPlaylist($id)) {
+ return "search";
+ } elseif (self::isVideo($id)) {
+ return "video";
+ } elseif (self::isPodcast($id)) {
+ return "podcast";
+ } elseif (self::isPodcastEp($id)) {
+ return "podcast_episode";
+ }
+
+ return "";
}
public static function createFailedResponse($version = "")
@@ -137,7 +198,9 @@ class Subsonic_XML_Data
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('');
$response->addAttribute('xmlns', 'http://subsonic.org/restapi');
$response->addAttribute('type', 'ampache');
@@ -147,7 +210,9 @@ class Subsonic_XML_Data
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);
self::setError($response, $code, $message);
return $response;
@@ -208,58 +273,75 @@ class Subsonic_XML_Data
self::addArtists($xindexes, $artists);
}
- public static function addArtistsRoot($xml, $artists)
+ public static function addArtistsRoot($xml, $artists, $albumsSet = false)
{
- $xartists = $xml->addChild('artists');
- self::addArtists($xartists, $artists, true);
+ $xartists = $xml->addChild('artists');
+ $ignoredArticles = AmpConfig::get('catalog_prefix_pattern');
+ if (!empty($ignoredArticles)) {
+ $ignoredArticles = str_replace("|", ",", $ignoredArticles);
+ $xartists->addAttribute('ignoredArticles', $ignoredArticles);
+ }
+ self::addArtists($xartists, $artists, true, $albumsSet);
}
- public static function addArtists($xml, $artists, $extra=false)
+ public static function addArtists($xml, $artists, $extra=false, $albumsSet = false)
{
- $xlastcat = null;
- $xsharpcat = null;
- $xlastletter = '';
+ $xlastcat = null;
+ $sharpartists = array();
+ $xlastletter = '';
foreach ($artists as $artist) {
if (strlen($artist->name) > 0) {
$letter = strtoupper($artist->name[0]);
- if ($letter == "X" || $letter == "Y" || $letter == "Z") $letter = "X-Z";
- else if (!preg_match("/^[A-W]$/", $letter)) $letter = "#";
+ if ($letter == "X" || $letter == "Y" || $letter == "Z") {
+ $letter = "X-Z";
+ } else {
+ if (!preg_match("/^[A-W]$/", $letter)) {
+ $sharpartists[] = $artist;
+ continue;
+ }
+ }
if ($letter != $xlastletter) {
$xlastletter = $letter;
- if ($letter == '#' && $xsharpcat != null) {
- $xlastcat = $xsharpcat;
- } else {
- $xlastcat = $xml->addChild('index');
- $xlastcat->addAttribute('name', $xlastletter);
-
- if ($letter == '#') {
- $xsharpcat = $xlastcat;
- }
- }
+ $xlastcat = $xml->addChild('index');
+ $xlastcat->addAttribute('name', $xlastletter);
}
}
if ($xlastcat != null) {
- self::addArtist($xlastcat, $artist, $extra);
+ self::addArtist($xlastcat, $artist, $extra, false, $albumsSet);
+ }
+ }
+
+ // Always add # index at the end
+ if (count($sharpartists) > 0) {
+ $xsharpcat = $xml->addChild('index');
+ $xsharpcat->addAttribute('name', '#');
+
+ foreach ($sharpartists as $artist) {
+ self::addArtist($xsharpcat, $artist, $extra, false, $albumsSet);
}
}
}
- public static function addArtist($xml, $artist, $extra=false, $albums=false)
+ public static function addArtist($xml, $artist, $extra=false, $albums=false, $albumsSet = false)
{
$xartist = $xml->addChild('artist');
$xartist->addAttribute('id', self::getArtistId($artist->id));
- $xartist->addAttribute('name', $artist->name);
+ $xartist->addAttribute('name', self::checkName($artist->name));
$allalbums = array();
- if ($extra || $albums) {
+ if (($extra && !$albumsSet) || $albums) {
$allalbums = $artist->get_albums(null, true);
}
if ($extra) {
- //$xartist->addAttribute('coverArt');
- $xartist->addAttribute('albumCount', count($allalbums));
+ $xartist->addAttribute('coverArt', 'ar-' . self::getArtistId($artist->id));
+ if ($albumsSet) {
+ $xartist->addAttribute('albumCount', $artist->albums);
+ } else {
+ $xartist->addAttribute('albumCount', count($allalbums));
+ }
}
if ($albums) {
foreach ($allalbums as $id) {
@@ -271,40 +353,40 @@ class Subsonic_XML_Data
public static function addAlbumList($xml, $albums, $elementName="albumList")
{
- $xlist = $xml->addChild(htmlspecialchars($elementName));
- foreach ($albums as $id) {
+ $xlist = $xml->addChild(htmlspecialchars($elementName));
+ foreach ($albums as $id) {
$album = new Album($id);
self::addAlbum($xlist, $album);
- }
+ }
}
- public static function addAlbum($xml, $album, $songs=false, $elementName="album")
+ public static function addAlbum($xml, $album, $songs=false, $addAmpacheInfo=false, $elementName="album")
{
$xalbum = $xml->addChild(htmlspecialchars($elementName));
$xalbum->addAttribute('id', self::getAlbumId($album->id));
- $xalbum->addAttribute('album', $album->name);
+ $xalbum->addAttribute('album', self::checkName($album->name));
$xalbum->addAttribute('title', self::formatAlbum($album, $elementName === "album"));
- $xalbum->addAttribute('name', $album->name);
+ $xalbum->addAttribute('name', self::checkName($album->name));
$xalbum->addAttribute('isDir', 'true');
$album->format();
if ($album->has_art) {
- $xalbum->addAttribute('coverArt', self::getAlbumId($album->id));
+ $xalbum->addAttribute('coverArt', 'al-' . self::getAlbumId($album->id));
}
$xalbum->addAttribute('songCount', $album->song_count);
$xalbum->addAttribute('duration', $album->total_duration);
$xalbum->addAttribute('artistId', self::getArtistId($album->artist_id));
$xalbum->addAttribute('parent', self::getArtistId($album->artist_id));
- $xalbum->addAttribute('artist', $album->artist_name);
+ $xalbum->addAttribute('artist', self::checkName($album->artist_name));
if ($album->year > 0) {
$xalbum->addAttribute('year', $album->year);
}
if (count($album->tags) > 0) {
$tag_values = array_values($album->tags);
- $tag = array_shift($tag_values);
+ $tag = array_shift($tag_values);
$xalbum->addAttribute('genre', $tag['name']);
}
- $rating = new Rating($album->id, "album");
+ $rating = new Rating($album->id, "album");
$user_rating = $rating->get_user_rating();
if ($user_rating > 0) {
$xalbum->addAttribute('userRating', ceil($user_rating));
@@ -318,36 +400,44 @@ class Subsonic_XML_Data
$allsongs = $album->get_songs();
foreach ($allsongs as $id) {
$song = new Song($id);
- self::addSong($xalbum, $song);
+ self::addSong($xalbum, $song, $addAmpacheInfo);
}
}
}
- public static function addSong($xml, $song, $elementName='song')
- {
- self::createSong($xml, $song, $elementName);
- }
-
- public static function createSong($xml, $song, $elementName='song')
+ public static function addSong($xml, $song, $addAmpacheInfo=false, $elementName='song')
{
+ self::createSong($xml, $song, $addAmpacheInfo, $elementName);
+ }
+
+ public static function createSong($xml, $song, $addAmpacheInfo=false, $elementName='song')
+ {
+ // Don't create entries for disabled songs
+ if (!$song->enabled) {
+ return null;
+ }
+
$xsong = $xml->addChild(htmlspecialchars($elementName));
$xsong->addAttribute('id', self::getSongId($song->id));
$xsong->addAttribute('parent', self::getAlbumId($song->album));
//$xsong->addAttribute('created', );
- $xsong->addAttribute('title', $song->title);
+ $xsong->addAttribute('title', self::checkName($song->title));
$xsong->addAttribute('isDir', 'false');
$xsong->addAttribute('isVideo', 'false');
$xsong->addAttribute('type', 'music');
$album = new Album($song->album);
$xsong->addAttribute('albumId', self::getAlbumId($album->id));
- $xsong->addAttribute('album', $album->name);
+ $xsong->addAttribute('album', self::checkName($album->name));
$artist = new Artist($song->artist);
$xsong->addAttribute('artistId', self::getArtistId($song->artist));
- $xsong->addAttribute('artist', $artist->name);
+ $xsong->addAttribute('artist', self::checkName($artist->name));
$xsong->addAttribute('coverArt', self::getAlbumId($album->id));
$xsong->addAttribute('duration', $song->time);
$xsong->addAttribute('bitRate', intval($song->bitrate / 1000));
- $rating = new Rating($song->id, "song");
+ if ($addAmpacheInfo) {
+ $xsong->addAttribute('playCount', $song->object_cnt);
+ }
+ $rating = new Rating($song->id, "song");
$user_rating = $rating->get_user_rating();
if ($user_rating > 0) {
$xsong->addAttribute('userRating', ceil($user_rating));
@@ -363,9 +453,13 @@ class Subsonic_XML_Data
$xsong->addAttribute('year', $song->year);
}
$tags = Tag::get_object_tags('song', $song->id);
- if (count($tags) > 0) $xsong->addAttribute('genre', $tags[0]['name']);
+ if (count($tags) > 0) {
+ $xsong->addAttribute('genre', $tags[0]['name']);
+ }
$xsong->addAttribute('size', $song->size);
- if ($album->disk > 0) $xsong->addAttribute('discNumber', $album->disk);
+ if ($album->disk > 0) {
+ $xsong->addAttribute('discNumber', $album->disk);
+ }
$xsong->addAttribute('suffix', $song->type);
$xsong->addAttribute('contentType', $song->mime);
// Create a clean fake path instead of song real file path to have better offline mode storage on Subsonic clients
@@ -374,7 +468,7 @@ class Subsonic_XML_Data
// Set transcoding information if required
$transcode_cfg = AmpConfig::get('transcode');
- $valid_types = Song::get_stream_types_for_type($song->type, 'api');
+ $valid_types = Song::get_stream_types_for_type($song->type, 'api');
if ($transcode_cfg == 'always' || ($transcode_cfg != 'never' && !in_array('native', $valid_types))) {
$transcode_settings = $song->get_transcode_settings(null, 'api');
if ($transcode_settings) {
@@ -398,6 +492,21 @@ class Subsonic_XML_Data
$name .= " [" . T_('Disk') . " " . $album->disk . "]";
}
+ return self::checkName($name);
+ }
+
+ private static function checkName($name)
+ {
+ // Ensure to have always a string type
+ // This to fix xml=>json which can result to wrong type parsing
+
+ if (self::$enable_json_checks && !empty($name)) {
+ if (is_numeric($name)) {
+ // Add space character to fail numeric test
+ // Yes, it is a trick but visually acceptable
+ $name = $name .= " ";
+ }
+ }
return $name;
}
@@ -410,7 +519,7 @@ class Subsonic_XML_Data
$allalbums = $artist->get_albums();
foreach ($allalbums as $id) {
$album = new Album($id);
- self::addAlbum($xdir, $album, false, "child");
+ self::addAlbum($xdir, $album, false, false, "child");
}
}
@@ -426,11 +535,11 @@ class Subsonic_XML_Data
$disc_ids = $album->get_group_disks_ids();
foreach ($disc_ids as $id) {
- $disc = new Album($id);
+ $disc = new Album($id);
$allsongs = $disc->get_songs();
foreach ($allsongs as $id) {
$song = new Song($id);
- self::addSong($xdir, $song, "child");
+ self::addSong($xdir, $song, false, "child");
}
}
}
@@ -440,8 +549,11 @@ class Subsonic_XML_Data
$xgenres = $xml->addChild('genres');
foreach ($tags as $tag) {
- $otag = new Tag($tag['id']);
- $xgenres->addChild('genre', htmlspecialchars($otag->name));
+ $otag = new Tag($tag['id']);
+ $xgenre = $xgenres->addChild('genre', htmlspecialchars($otag->name));
+ $counts = $otag->count('', $GLOBALS['user']->id);
+ $xgenre->addAttribute("songCount", $counts['song']);
+ $xgenre->addAttribute("albumCount", $counts['album']);
}
}
@@ -454,9 +566,9 @@ class Subsonic_XML_Data
}
}
- public static function addVideo($xml, $video)
+ public static function addVideo($xml, $video, $elementName = 'video')
{
- $xvideo = $xml->addChild('video');
+ $xvideo = $xml->addChild($elementName);
$xvideo->addAttribute('id', self::getVideoId($video->id));
$xvideo->addAttribute('title', $video->f_full_title);
$xvideo->addAttribute('isDir', 'false');
@@ -468,7 +580,9 @@ class Subsonic_XML_Data
$xvideo->addAttribute('year', $video->year);
}
$tags = Tag::get_object_tags('video', $video->id);
- if (count($tags) > 0) $xvideo->addAttribute('genre', $tags[0]['name']);
+ if (count($tags) > 0) {
+ $xvideo->addAttribute('genre', $tags[0]['name']);
+ }
$xvideo->addAttribute('size', $video->size);
$xvideo->addAttribute('suffix', $video->type);
$xvideo->addAttribute('contentType', $video->mime);
@@ -478,7 +592,7 @@ class Subsonic_XML_Data
// Set transcoding information if required
$transcode_cfg = AmpConfig::get('transcode');
- $valid_types = Song::get_stream_types_for_type($video->type, 'api');
+ $valid_types = Song::get_stream_types_for_type($video->type, 'api');
if ($transcode_cfg == 'always' || ($transcode_cfg != 'never' && !in_array('native', $valid_types))) {
$transcode_settings = $video->get_transcode_settings(null, 'api');
if ($transcode_settings) {
@@ -511,14 +625,14 @@ class Subsonic_XML_Data
$xplaylist->addAttribute('owner', $user->username);
$xplaylist->addAttribute('public', ($playlist->type != "private") ? "true" : "false");
$xplaylist->addAttribute('created', date("c", $playlist->date));
- $xplaylist->addAttribute('songCount', $playlist->get_song_count());
+ $xplaylist->addAttribute('songCount', $playlist->get_media_count('song'));
$xplaylist->addAttribute('duration', $playlist->get_total_duration());
if ($songs) {
$allsongs = $playlist->get_songs();
foreach ($allsongs as $id) {
$song = new Song($id);
- self::addSong($xplaylist, $song, "entry");
+ self::addSong($xplaylist, $song, false, "entry");
}
}
}
@@ -536,7 +650,7 @@ class Subsonic_XML_Data
$allitems = $playlist->get_items();
foreach ($allitems as $item) {
$song = new Song($item['object_id']);
- self::addSong($xplaylist, $song, "entry");
+ self::addSong($xplaylist, $song, false, "entry");
}
}
}
@@ -563,10 +677,12 @@ class Subsonic_XML_Data
{
$xplaynow = $xml->addChild('nowPlaying');
foreach ($data as $d) {
- $track = self::createSong($xplaynow, $d['media'], "entry");
- $track->addAttribute('username', $d['client']->username);
- $track->addAttribute('minutesAgo', intval(time() - ($d['expire'] - AmpConfig::get('stream_length')) / 1000));
- $track->addAttribute('playerId', $d['agent']);
+ $track = self::createSong($xplaynow, $d['media'], false, "entry");
+ if ($track !== null) {
+ $track->addAttribute('username', $d['client']->username);
+ $track->addAttribute('minutesAgo', intval(time() - ($d['expire'] - AmpConfig::get('stream_length')) / 1000));
+ $track->addAttribute('playerId', $d['agent']);
+ }
}
}
@@ -614,7 +730,7 @@ class Subsonic_XML_Data
$xuser->addAttribute('email', $user->email);
$xuser->addAttribute('scrobblingEnabled', 'true');
$isManager = ($user->access >= 75);
- $isAdmin = ($user->access >= 100);
+ $isAdmin = ($user->access >= 100);
$xuser->addAttribute('adminRole', $isAdmin ? 'true' : 'false');
$xuser->addAttribute('settingsRole', 'true');
$xuser->addAttribute('downloadRole', Preference::get_by_user($user->id, 'download') ? 'true' : 'false');
@@ -673,20 +789,20 @@ class Subsonic_XML_Data
if ($share->object_type == 'song') {
$song = new Song($share->object_id);
- self::addSong($xshare, $song, "entry");
+ self::addSong($xshare, $song, false, "entry");
} elseif ($share->object_type == 'playlist') {
$playlist = new Playlist($share->object_id);
- $songs = $playlist->get_songs();
+ $songs = $playlist->get_songs();
foreach ($songs as $id) {
$song = new Song($id);
- self::addSong($xshare, $song, "entry");
+ self::addSong($xshare, $song, false, "entry");
}
} elseif ($share->object_type == 'album') {
$album = new Album($share->object_id);
$songs = $album->get_songs();
foreach ($songs as $id) {
$song = new Song($id);
- self::addSong($xshare, $song, "entry");
+ self::addSong($xshare, $song, false, "entry");
}
}
}
@@ -705,19 +821,19 @@ class Subsonic_XML_Data
public static function addJukeboxPlaylist($xml, Localplay $localplay)
{
- $xjbox = self::createJukeboxStatus($xml, $localplay, 'jukeboxPlaylist');
+ $xjbox = self::createJukeboxStatus($xml, $localplay, 'jukeboxPlaylist');
$tracks = $localplay->get();
foreach ($tracks as $track) {
if ($track['oid']) {
$song = new Song($track['oid']);
- self::createSong($xjbox, $song, 'entry');
+ self::createSong($xjbox, $song, false, 'entry');
}
}
}
public static function createJukeboxStatus($xml, Localplay $localplay, $elementName = 'jukeboxStatus')
{
- $xjbox = $xml->addChild($elementName);
+ $xjbox = $xml->addChild($elementName);
$status = $localplay->status();
$xjbox->addAttribute('currentIndex', 0); // Not supported
$xjbox->addAttribute('playing', ($status['state'] == 'play') ? 'true' : 'false');
@@ -735,8 +851,8 @@ class Subsonic_XML_Data
$lyrics = $song->get_lyrics();
if ($lyrics && $lyrics['text']) {
- $text = preg_replace('/\ /i', "\n", $lyrics['text']);
- $text = str_replace("\r", '', $text);
+ $text = preg_replace('/\ /i', "\n", $lyrics['text']);
+ $text = str_replace("\r", '', $text);
$xlyrics = $xml->addChild("lyrics", $text);
if ($artist) {
$xlyrics->addAttribute("artist", $artist);
@@ -762,7 +878,7 @@ class Subsonic_XML_Data
foreach ($similars as $similar) {
$xsimilar = $xartist->addChild("similarArtist");
$xsimilar->addAttribute("id", ($similar['id'] !== null ? self::getArtistId($similar['id']) : "-1"));
- $xsimilar->addAttribute("name", $similar['name']);
+ $xsimilar->addAttribute("name", self::checkName($similar['name']));
}
}
@@ -777,4 +893,91 @@ class Subsonic_XML_Data
}
}
}
+
+ public static function addPodcasts($xml, $podcasts, $includeEpisodes = false)
+ {
+ $xpodcasts = $xml->addChild("podcasts");
+ foreach ($podcasts as $podcast) {
+ $podcast->format();
+ $xchannel = $xpodcasts->addChild("channel");
+ $xchannel->addAttribute("id", self::getPodcastId($podcast->id));
+ $xchannel->addAttribute("url", $podcast->feed);
+ $xchannel->addAttribute("title", self::checkName($podcast->f_title));
+ $xchannel->addAttribute("description", $podcast->f_description);
+ if (Art::has_db($podcast->id, 'podcast')) {
+ $xchannel->addAttribute("coverArt", "pod-" . self::getPodcastId($podcast->id));
+ }
+ $xchannel->addAttribute("status", "completed");
+ if ($includeEpisodes) {
+ $episodes = $podcast->get_episodes();
+ foreach ($episodes as $episode_id) {
+ $episode = new Podcast_Episode($episode_id);
+ self::addPodcastEpisode($xchannel, $episode);
+ }
+ }
+ }
+ }
+
+ private static function addPodcastEpisode($xml, $episode, $elementName = 'episode')
+ {
+ $episode->format();
+ $xepisode = $xml->addChild($elementName);
+ $xepisode->addAttribute("id", self::getPodcastEpId($episode->id));
+ $xepisode->addAttribute("channelId", self::getPodcastId($episode->podcast));
+ $xepisode->addAttribute("title", $episode->f_title);
+ $xepisode->addAttribute("album", $episode->f_podcast);
+ $xepisode->addAttribute("description", $episode->f_description);
+ $xepisode->addAttribute("duration", $episode->time);
+ $xepisode->addAttribute("genre", "Podcast");
+ $xepisode->addAttribute("isDir", "false");
+ $xepisode->addAttribute("publishDate", date("c", $episode->pubdate));
+ $xepisode->addAttribute("status", $episode->state);
+ if (Art::has_db($episode->podcast, 'podcast')) {
+ $xepisode->addAttribute("coverArt",self::getPodcastId($episode->podcast));
+ }
+ if ($episode->file) {
+ $xepisode->addAttribute("streamId", self::getPodcastEpId($episode->id));
+ $xepisode->addAttribute("size", $episode->size);
+ $xepisode->addAttribute("suffix", $episode->type);
+ $xepisode->addAttribute("contentType", $episode->mime);
+ // Create a clean fake path instead of song real file path to have better offline mode storage on Subsonic clients
+ $path = basename($episode->file);
+ $xepisode->addAttribute("path", $path);
+ }
+ }
+
+ public static function addNewestPodcastEpisodes($xml, $episodes)
+ {
+ $xpodcasts = $xml->addChild("newestPodcasts");
+ foreach ($episodes as $episode) {
+ $episode->format();
+ self::addPodcastEpisode($xpodcasts, $episode);
+ }
+ }
+
+ public static function addBookmarks($xml, $bookmarks)
+ {
+ $xbookmarks = $xml->addChild("bookmarks");
+ foreach ($bookmarks as $bookmark) {
+ $bookmark->format();
+ self::addBookmark($xbookmarks, $bookmark);
+ }
+ }
+
+ private static function addBookmark($xml, $bookmark)
+ {
+ $xbookmark = $xml->addChild("bookmark");
+ $xbookmark->addAttribute("position", $bookmark->position);
+ $xbookmark->addAttribute("username", $bookmark->f_user);
+ $xbookmark->addAttribute("comment", $bookmark->comment);
+ $xbookmark->addAttribute("created", date("c", $bookmark->creation_date));
+ $xbookmark->addAttribute("changed", date("c", $bookmark->update_date));
+ if ($bookmark->object_type == "song") {
+ self::addSong($xbookmark, new Song($bookmark->object_id), false, 'entry');
+ } elseif ($bookmark->object_type == "video") {
+ self::addVideo($xbookmark, new Video($bookmark->object_id), 'entry');
+ } elseif ($bookmark->object_type == "podcast_episode") {
+ self::addPodcastEpisode($xbookmark, new Podcast_Episode($bookmark->object_id), 'entry');
+ }
+ }
}
diff --git a/sources/lib/class/tag.class.php b/sources/lib/class/tag.class.php
index b83151c..a910297 100644
--- a/sources/lib/class/tag.class.php
+++ b/sources/lib/class/tag.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -38,14 +38,15 @@ class Tag extends database_object implements library_item
*/
public function __construct($id)
{
- if (!$id) { return false; }
+ if (!$id) {
+ return false;
+ }
$info = $this->get_info($id);
foreach ($info as $key=>$value) {
$this->$key = $value;
} // end foreach
-
} // constructor
/**
@@ -59,7 +60,6 @@ class Tag extends database_object implements library_item
$tag = new Tag($tag_id);
return $tag;
-
} // construct_from_name
/**
@@ -69,11 +69,13 @@ class Tag extends database_object implements library_item
*/
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) . ')';
- $sql = "SELECT * FROM `tag` WHERE `id` IN $idlist";
+ $sql = "SELECT * FROM `tag` WHERE `id` IN $idlist";
$db_results = Dba::read($sql);
while ($row = Dba::fetch_assoc($db_results)) {
@@ -89,10 +91,13 @@ class Tag extends database_object implements library_item
*/
public static function build_map_cache($type, $ids)
{
- if (!is_array($ids) OR !count($ids)) { return false; }
-
- if (!Core::is_library_item($type))
+ if (!is_array($ids) or !count($ids)) {
return false;
+ }
+
+ if (!Core::is_library_item($type)) {
+ return false;
+ }
$idlist = '(' . implode(',',$ids) . ')';
@@ -102,18 +107,18 @@ class Tag extends database_object implements library_item
$db_results = Dba::read($sql);
- $tags = array();
+ $tags = array();
$tag_map = array();
while ($row = Dba::fetch_assoc($db_results)) {
$tags[$row['object_id']][$row['tag_id']] = array('user'=>$row['user'], 'id'=>$row['tag_id'], 'name'=>$row['name']);
- $tag_map[$row['object_id']] = array('id'=>$row['id'],'tag_id'=>$row['tag_id'],'user'=>$row['user'],'object_type'=>$type,'object_id'=>$row['object_id']);
+ $tag_map[$row['object_id']] = array('id'=>$row['id'],'tag_id'=>$row['tag_id'],'user'=>$row['user'],'object_type'=>$type,'object_id'=>$row['object_id']);
}
// Run through our original ids as we also want to cache NULL
// results
foreach ($ids as $id) {
if (!isset($tags[$id])) {
- $tags[$id] = null;
+ $tags[$id] = null;
$tag_map[$id] = null;
}
parent::add_to_cache('tag_top_' . $type, $id, $tags[$id]);
@@ -121,7 +126,6 @@ class Tag extends database_object implements library_item
}
return true;
-
} // build_map_cache
/**
@@ -131,14 +135,19 @@ class Tag extends database_object implements library_item
*/
public static function add($type, $id, $value, $user=false)
{
- if (!Core::is_library_item($type))
+ if (!Core::is_library_item($type)) {
return false;
+ }
- if (!is_numeric($id)) { return false; }
+ if (!is_numeric($id)) {
+ return false;
+ }
$cleaned_value = $value;
- if (!strlen($cleaned_value)) { return false; }
+ if (!strlen($cleaned_value)) {
+ return false;
+ }
$uid = ($user === false) ? intval($user) : intval($GLOBALS['user']->id);
@@ -158,7 +167,6 @@ class Tag extends database_object implements library_item
}
return $map_id;
-
} // add
/**
@@ -167,7 +175,9 @@ class Tag extends database_object implements library_item
*/
public static function add_tag($value)
{
- if (!strlen($value)) { return false; }
+ if (!strlen($value)) {
+ return false;
+ }
$sql = "REPLACE INTO `tag` SET `name` = ?";
Dba::write($sql, array($value));
@@ -176,7 +186,6 @@ class Tag extends database_object implements library_item
parent::add_to_cache('tag_name', $value, $insert_id);
return $insert_id;
-
} // add_tag
/**
@@ -186,7 +195,9 @@ class Tag extends database_object implements library_item
public function update(array $data)
{
//debug_event('tag.class', 'Updating tag {'.$this->id.'} with name {'.$name.'}...', '5');
- if (!strlen($data['name'])) { return false; }
+ if (!strlen($data['name'])) {
+ return false;
+ }
$sql = 'UPDATE `tag` SET `name` = ? WHERE `id` = ?';
Dba::write($sql, array($data[name], $this->id));
@@ -213,7 +224,6 @@ class Tag extends database_object implements library_item
}
}
return $this->id;
-
} // add_tag
/**
@@ -229,7 +239,7 @@ class Tag extends database_object implements library_item
"SELECT ?,`user`,`object_type`,`object_id` " .
"FROM `tag_map` AS `tm`" .
"WHERE `tm`.`tag_id` = ? AND NOT EXISTS ( " .
- "SELECT 1 FROM `tag_map` ".
+ "SELECT 1 FROM `tag_map` " .
"WHERE `tag_map`.`tag_id` = ? " .
"AND `tag_map`.`object_id` = `tm`.`object_id` " .
"AND `tag_map`.`object_type` = `tm`.`object_type` " .
@@ -251,7 +261,7 @@ class Tag extends database_object implements library_item
{
$sql = "SELECT `tag`.`id`, `tag`.`name`" .
"FROM `tag_merge` " .
- "INNER JOIN `tag` ON `tag`.`id` = `tag_merge`.`merged_to` ".
+ "INNER JOIN `tag` ON `tag`.`id` = `tag_merge`.`merged_to` " .
"WHERE `tag_merge`.`tag_id` = ? " .
"ORDER BY `tag`.`name` ";
@@ -271,18 +281,22 @@ class Tag extends database_object implements library_item
*/
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);
- if (!Core::is_library_item($type))
+ if (!Core::is_library_item($type)) {
+ debug_event('tag.class', $type . " is not a library item.", 3);
return false;
+ }
$id = intval($object_id);
- if (!$tag_id || !$id) { return false; }
+ if (!$tag_id || !$id) {
+ return false;
+ }
// If tag merged to another one, add reference to the merge destination
$parent = new Tag($tag_id);
$merges = $parent->get_merged_tags();
- if ($parent->is_hidden == false) {
+ if (!$parent->is_hidden) {
$merges[] = array('id' => $parent->id, 'name' => $parent->name);
}
foreach ($merges as $tag) {
@@ -295,7 +309,6 @@ class Tag extends database_object implements library_item
parent::add_to_cache('tag_map_' . $type,$insert_id,array('tag_id'=>$tag_id,'user'=>$uid,'object_type'=>$type,'object_id'=>$id));
return $insert_id;
-
} // add_tag_map
/**
@@ -352,7 +365,7 @@ class Tag extends database_object implements library_item
Dba::write($sql, array($this->id));
$sql = "DELETE FROM `tag` WHERE `tag`.`id` = ? ";
- Dba::write($sql, array($this->id, $this->id));
+ Dba::write($sql, array($this->id));
// Call the garbage collector to clean everything
Tag::gc();
@@ -370,7 +383,7 @@ class Tag extends database_object implements library_item
return parent::get_from_cache('tag_name',$value);
}
- $sql = "SELECT * FROM `tag` WHERE `name` = ?";
+ $sql = "SELECT * FROM `tag` WHERE `name` = ?";
$db_results = Dba::read($sql, array($value));
$results = Dba::fetch_assoc($db_results);
@@ -378,7 +391,6 @@ class Tag extends database_object implements library_item
parent::add_to_cache('tag_name',$results['name'],$results['id']);
return $results['id'];
-
} // tag_exists
/**
@@ -388,8 +400,9 @@ class Tag extends database_object implements library_item
*/
public static function tag_map_exists($type,$object_id,$tag_id,$user)
{
- if (!Core::is_library_item($type))
+ if (!Core::is_library_item($type)) {
return false;
+ }
$sql = "SELECT * FROM `tag_map` LEFT JOIN `tag` ON `tag`.`id` = `tag_map`.`tag_id` LEFT JOIN `tag_merge` ON `tag`.`id`=`tag_merge`.`tag_id` " .
"WHERE (`tag_map`.`tag_id` = ? OR `tag_map`.`tag_id` = `tag_merge`.`merged_to`) AND `tag_map`.`user` = ? AND `tag_map`.`object_id` = ? AND `tag_map`.`object_type` = ?";
@@ -398,7 +411,6 @@ class Tag extends database_object implements library_item
$results = Dba::fetch_assoc($db_results);
return $results['id'];
-
} // tag_map_exists
/**
@@ -407,16 +419,17 @@ class Tag extends database_object implements library_item
*/
public static function get_top_tags($type, $object_id, $limit = 10)
{
- if (!Core::is_library_item($type))
+ if (!Core::is_library_item($type)) {
return array();
+ }
$object_id = intval($object_id);
$limit = intval($limit);
- $sql = "SELECT `tag_map`.`id`, `tag_map`.`tag_id`, `tag`.`name`, `tag_map`.`user` FROM `tag` " .
+ $sql = "SELECT `tag_map`.`id`, `tag_map`.`tag_id`, `tag`.`name`, `tag_map`.`user` FROM `tag` " .
"LEFT JOIN `tag_map` ON `tag_map`.`tag_id`=`tag`.`id` " .
- "WHERE `tag_map`.`object_type`='$type' AND `tag_map`.`object_id`='$object_id' ".
- "GROUP BY `tag`.`name` LIMIT $limit";
+ "WHERE `tag_map`.`object_type`='$type' AND `tag_map`.`object_id`='$object_id' " .
+ "LIMIT $limit";
$db_results = Dba::read($sql);
@@ -427,7 +440,6 @@ class Tag extends database_object implements library_item
}
return $results;
-
} // get_top_tags
/**
@@ -437,14 +449,15 @@ class Tag extends database_object implements library_item
*/
public static function get_object_tags($type, $id)
{
- if (!Core::is_library_item($type))
+ if (!Core::is_library_item($type)) {
return false;
+ }
$sql = "SELECT `tag_map`.`id`, `tag`.`name`, `tag_map`.`user` FROM `tag` " .
"LEFT JOIN `tag_map` ON `tag_map`.`tag_id`=`tag`.`id` " .
"WHERE `tag_map`.`object_type` = ? AND `tag_map`.`object_id` = ?";
- $results = array();
+ $results = array();
$db_results = Dba::read($sql, array($type, $id));
while ($row = Dba::fetch_assoc($db_results)) {
@@ -460,13 +473,16 @@ class Tag extends database_object implements library_item
*/
public static function get_tag_objects($type,$tag_id,$count='',$offset='')
{
- if (!Core::is_library_item($type))
+ if (!Core::is_library_item($type)) {
return false;
+ }
$limit_sql = "";
if ($count) {
$limit_sql = "LIMIT ";
- if ($offset) $limit_sql .= intval($offset) . ',';
+ if ($offset) {
+ $limit_sql .= intval($offset) . ',';
+ }
$limit_sql .= intval($count);
}
@@ -504,7 +520,8 @@ class Tag extends database_object implements library_item
$sql = "SELECT `tag_map`.`tag_id`, `tag`.`name`, `tag`.`is_hidden`, COUNT(`tag_map`.`object_id`) AS `count` " .
"FROM `tag_map` " .
"LEFT JOIN `tag` ON `tag`.`id`=`tag_map`.`tag_id` " .
- "WHERE `tag`.`is_hidden` = false ";
+ "WHERE `tag`.`is_hidden` = false " .
+ "GROUP BY `tag_map`.`tag_id`, `tag`.`name`, `tag`.`is_hidden` ";
if (!empty($type)) {
$sql .= "AND `tag_map`.`object_type` = '" . scrub_in($type) . "' ";
}
@@ -512,21 +529,19 @@ class Tag extends database_object implements library_item
if ($order == 'count') {
$order .= " DESC";
}
- $sql .="GROUP BY `tag`.`name` ORDER BY " . $order;
+ $sql .= "ORDER BY " . $order;
if ($limit > 0) {
$sql .= " LIMIT $limit";
}
$db_results = Dba::read($sql);
-
while ($row = Dba::fetch_assoc($db_results)) {
$results[$row['tag_id']] = array('id'=>$row['tag_id'], 'name'=>$row['name'], 'is_hidden'=>$row['is_hidden'], 'count'=>$row['count']);
}
parent::add_to_cache('tags_list', 'no_name', $results);
return $results;
-
} // get_tags
/**
@@ -538,7 +553,9 @@ class Tag extends database_object implements library_item
public static function get_display($tags, $link=false, $filter_type='')
{
//debug_event('tag.class.php', 'Get display tags called...', '5');
- if (!is_array($tags)) { return ''; }
+ if (!is_array($tags)) {
+ return '';
+ }
$results = '';
@@ -561,7 +578,6 @@ class Tag extends database_object implements library_item
$results = rtrim($results, ', ');
return $results;
-
} // get_display
/**
@@ -570,16 +586,16 @@ class Tag extends database_object implements library_item
*/
public static function update_tag_list($tags_comma, $type, $object_id, $overwrite)
{
- debug_event('tag.class', 'Updating tags for values {'.$tags_comma.'} type {'.$type.'} object_id {'.$object_id.'}', '5');
+ debug_event('tag.class', 'Updating tags for values {' . $tags_comma . '} type {' . $type . '} object_id {' . $object_id . '}', '5');
- $ctags = Tag::get_top_tags($type, $object_id);
+ $ctags = Tag::get_top_tags($type, $object_id);
$editedTags = explode(",", $tags_comma);
if (is_array($ctags)) {
foreach ($ctags as $ctid => $ctv) {
if ($ctv['id'] != '') {
$ctag = new Tag($ctv['id']);
- debug_event('tag.class', 'Processing tag {'.$ctag->name.'}...', '5');
+ debug_event('tag.class', 'Processing tag {' . $ctag->name . '}...', '5');
$found = false;
foreach ($editedTags as $tk => $tv) {
@@ -592,9 +608,11 @@ class Tag extends database_object implements library_item
if ($found) {
debug_event('tag.class', 'Already found. Do nothing.', '5');
unset($editedTags[$tk]);
- } else if ($overwrite) {
- debug_event('tag.class', 'Not found in the new list. Delete it.', '5');
- $ctag->remove_map($type, $object_id);
+ } else {
+ if ($overwrite) {
+ debug_event('tag.class', 'Not found in the new list. Delete it.', '5');
+ $ctag->remove_map($type, $object_id);
+ }
}
}
}
@@ -603,7 +621,7 @@ class Tag extends database_object implements library_item
// Look if we need to add some new tags
foreach ($editedTags as $tk => $tv) {
if ($tv != '') {
- debug_event('tag.class', 'Adding new tag {'.$tv.'}', '5');
+ debug_event('tag.class', 'Adding new tag {' . $tv . '}', '5');
Tag::add($type, $object_id, $tv, false);
}
}
@@ -641,24 +659,30 @@ class Tag extends database_object implements library_item
* This returns the count for the all objects associated with this tag
* If a type is specific only counts for said type are returned
*/
- public function count($type='')
+ public function count($type='', $user_id = 0)
{
+ $params = array($this->id);
+
$filter_sql = "";
+ if ($user_id > 0) {
+ $filter_sql = " AND `user` = ?";
+ $params[] = $user_id;
+ }
if ($type) {
- $filter_sql = " AND `object_type`='" . Dba::escape($type) . "'";
+ $filter_sql = " AND `object_type` = ?";
+ $params[] = $type;
}
$results = array();
- $sql = "SELECT COUNT(`id`) AS `count`,`object_type` FROM `tag_map` WHERE `tag_id`='" . Dba::escape($this->id) . "'" . $filter_sql . " GROUP BY `object_type`";
- $db_results = Dba::read($sql);
+ $sql = "SELECT DISTINCT(`object_type`), COUNT(`object_id`) AS `count` FROM `tag_map` WHERE `tag_id` = ?" . $filter_sql . " GROUP BY `object_type`";
+ $db_results = Dba::read($sql, $params);
while ($row = Dba::fetch_assoc($db_results)) {
$results[$row['object_type']] = $row['count'];
}
return $results;
-
} // count
/**
@@ -667,8 +691,9 @@ class Tag extends database_object implements library_item
*/
public function remove_map($type, $object_id)
{
- if (!Core::is_library_item($type))
+ if (!Core::is_library_item($type)) {
return false;
+ }
// TODO: Review the tag edition per user.
@@ -676,17 +701,15 @@ class Tag extends database_object implements library_item
Dba::write($sql, array($this->id, $type, $object_id));//, $GLOBALS['user']->id));
return true;
-
} // remove_map
public function format($details = true)
{
-
}
public function get_keywords()
{
- $keywords = array();
+ $keywords = array();
$keywords['tag'] = array('important' => true,
'label' => T_('Tag'),
'value' => $this->name);
@@ -763,5 +786,5 @@ class Tag extends database_object implements library_item
Art::display('tag', $this->id, $this->get_fullname(), $thumb, $this->link);
}
}
-
} // end of Tag class
+
diff --git a/sources/lib/class/tmp_playlist.class.php b/sources/lib/class/tmp_playlist.class.php
index 85896bc..768a787 100644
--- a/sources/lib/class/tmp_playlist.class.php
+++ b/sources/lib/class/tmp_playlist.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -48,7 +48,9 @@ class Tmp_Playlist extends database_object
*/
public function __construct($playlist_id='')
{
- if (!$playlist_id) { return false; }
+ if (!$playlist_id) {
+ return false;
+ }
$this->id = intval($playlist_id);
$info = $this->_get_info();
@@ -58,7 +60,6 @@ class Tmp_Playlist extends database_object
}
return true;
-
} // __construct
/**
@@ -68,13 +69,12 @@ class Tmp_Playlist extends database_object
*/
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);
$results = Dba::fetch_assoc($db_results);
return $results;
-
} // _get_info
/**
@@ -86,7 +86,7 @@ class Tmp_Playlist extends database_object
{
$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'";
$db_results = Dba::read($sql);
$results = Dba::fetch_row($db_results);
@@ -102,7 +102,6 @@ class Tmp_Playlist extends database_object
$playlist = new Tmp_Playlist($results['0']);
return $playlist;
-
} // get_from_session
/**
@@ -115,7 +114,7 @@ class Tmp_Playlist extends database_object
// 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
// to do it this way.
- $client = new User($user_id);
+ $client = new User($user_id);
$username = Dba::escape($client->username);
$sql = "SELECT `tmp_playlist`.`id` FROM `tmp_playlist` " .
@@ -128,7 +127,6 @@ class Tmp_Playlist extends database_object
$data = Dba::fetch_assoc($db_results);
return $data['id'];
-
} // get_from_userid
/**
@@ -157,7 +155,6 @@ class Tmp_Playlist extends database_object
}
return $items;
-
} // get_items
/**
@@ -175,7 +172,6 @@ class Tmp_Playlist extends database_object
$results = Dba::fetch_assoc($db_results);
return $results['object_id'];
-
} // get_next_object
/**
@@ -194,7 +190,6 @@ class Tmp_Playlist extends database_object
$results = Dba::fetch_row($db_results);
return $results['0'];
-
} // count_items
/**
@@ -207,7 +202,6 @@ class Tmp_Playlist extends database_object
Dba::write($sql, array($this->id));
return true;
-
} // clear
/**
@@ -229,7 +223,6 @@ class Tmp_Playlist extends database_object
self::session_clean($data['session_id'], $id);
return $id;
-
} // create
/**
@@ -243,7 +236,6 @@ class Tmp_Playlist extends database_object
Dba::write($sql, array($playlist_id, $this->id));
return true;
-
} // update_playlist
/**
@@ -260,7 +252,6 @@ class Tmp_Playlist extends database_object
self::prune_tracks();
return true;
-
} // session_clean
/**
@@ -289,7 +280,6 @@ class Tmp_Playlist extends database_object
Dba::write($sql);
return true;
-
} // prune_playlists
/**
@@ -305,7 +295,6 @@ class Tmp_Playlist extends database_object
"`tmp_playlist_data`.`tmp_playlist`=`tmp_playlist`.`id` " .
"WHERE `tmp_playlist`.`id` IS NULL";
Dba::write($sql);
-
} // prune_tracks
/**
@@ -321,7 +310,6 @@ class Tmp_Playlist extends database_object
Dba::write($sql, array($object_id, $this->id, $object_type));
return true;
-
} // add_object
public function add_medias($medias)
@@ -339,10 +327,11 @@ class Tmp_Playlist extends database_object
public function vote_active()
{
/* Going to do a little more here later */
- if ($this->type == 'vote') { return true; }
+ if ($this->type == 'vote') {
+ return true;
+ }
return false;
-
} // vote_active
/**
@@ -356,7 +345,6 @@ class Tmp_Playlist extends database_object
Dba::write($sql, array($id));
return true;
-
} // delete_track
-
} // class Tmp_Playlist
+
diff --git a/sources/lib/class/tvshow.class.php b/sources/lib/class/tvshow.class.php
index 9cc5dfa..9ab5e06 100644
--- a/sources/lib/class/tvshow.class.php
+++ b/sources/lib/class/tvshow.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -49,7 +49,9 @@ class TVShow extends database_object implements library_item
public function __construct($id='')
{
/* If they failed to pass in an id, just run for it */
- if (!$id) { return false; }
+ if (!$id) {
+ return false;
+ }
/* Get the information from the db */
$info = $this->get_info($id);
@@ -59,7 +61,6 @@ class TVShow extends database_object implements library_item
} // foreach info
return true;
-
} //constructor
/**
@@ -80,14 +81,13 @@ class TVShow extends database_object implements library_item
*/
public static function get_from_name($name)
{
- $sql = "SELECT `id` FROM `tvshow` WHERE `name` = ?'";
+ $sql = "SELECT `id` FROM `tvshow` WHERE `name` = ?'";
$db_results = Dba::read($sql, array($name));
$row = Dba::fetch_assoc($db_results);
$object = new TVShow($row['id']);
return $object;
-
} // get_from_name
/**
@@ -97,19 +97,18 @@ class TVShow extends database_object implements library_item
*/
public function get_seasons()
{
- $sql = "SELECT `id` FROM `tvshow_season` WHERE `tvshow` = ? ORDER BY `season_number`";
+ $sql = "SELECT `id` FROM `tvshow_season` WHERE `tvshow` = ? ORDER BY `season_number`";
$db_results = Dba::read($sql, array($this->id));
- $results = array();
+ $results = array();
while ($r = Dba::fetch_assoc($db_results)) {
$results[] = $r['id'];
}
return $results;
-
} // get_seasons
/**
- * get_songs
+ * get_episodes
* gets all episodes for this tv show
*/
public function get_episodes()
@@ -133,7 +132,6 @@ class TVShow extends database_object implements library_item
}
return $results;
-
} // get_episodes
/**
@@ -151,24 +149,23 @@ class TVShow extends database_object implements library_item
"LEFT JOIN `video` ON `video`.`id` = `tvshow_episode`.`id` " .
"WHERE `tvshow_season`.`tvshow` = ?";
$db_results = Dba::read($sql, array($this->id));
- $row = Dba::fetch_assoc($db_results);
+ $row = Dba::fetch_assoc($db_results);
$sql = "SELECT COUNT(`tvshow_season`.`id`) AS `season_count` FROM `tvshow_season` " .
"WHERE `tvshow_season`.`tvshow` = ?";
- $db_results = Dba::read($sql, array($this->id));
- $row2 = Dba::fetch_assoc($db_results);
+ $db_results = Dba::read($sql, array($this->id));
+ $row2 = Dba::fetch_assoc($db_results);
$row['season_count'] = $row2['season_count'];
parent::add_to_cache('tvshow_extra',$this->id,$row);
}
/* Set Object Vars */
- $this->episodes = $row['episode_count'];
- $this->seasons = $row['season_count'];
+ $this->episodes = $row['episode_count'];
+ $this->seasons = $row['season_count'];
$this->catalog_id = $row['catalog_id'];
return $row;
-
} // _get_extra_info
/**
@@ -178,12 +175,12 @@ class TVShow extends database_object implements library_item
public function format($details = true)
{
$this->f_name = trim($this->prefix . " " . $this->name);
- $this->link = AmpConfig::get('web_path') . '/tvshows.php?action=show&tvshow=' . $this->id;
+ $this->link = AmpConfig::get('web_path') . '/tvshows.php?action=show&tvshow=' . $this->id;
$this->f_link = '' . $this->f_name . '';
if ($details) {
$this->_get_extra_info();
- $this->tags = Tag::get_top_tags('tvshow', $this->id);
+ $this->tags = Tag::get_top_tags('tvshow', $this->id);
$this->f_tags = Tag::get_display($this->tags, true, 'tvshow');
}
@@ -192,7 +189,7 @@ class TVShow extends database_object implements library_item
public function get_keywords()
{
- $keywords = array();
+ $keywords = array();
$keywords['tvshow'] = array('important' => true,
'label' => T_('TV Show'),
'value' => $this->f_name);
@@ -277,32 +274,32 @@ class TVShow extends database_object implements library_item
*
* Checks for an existing tv show; if none exists, insert one.
*/
- public static function check($name, $year, $readonly = false)
+ public static function check($name, $year, $tvshow_summary, $readonly = false)
{
// null because we don't have any unique id like mbid for now
if (isset(self::$_mapcache[$name]['null'])) {
return self::$_mapcache[$name]['null'];
}
- $id = 0;
+ $id = 0;
$exists = false;
$trimmed = Catalog::trim_prefix(trim($name));
- $name = $trimmed['string'];
- $prefix = $trimmed['prefix'];
+ $name = $trimmed['string'];
+ $prefix = $trimmed['prefix'];
if (!$exists) {
- $sql = 'SELECT `id` FROM `tvshow` WHERE `name` LIKE ? AND `year` = ?';
+ $sql = 'SELECT `id` FROM `tvshow` WHERE `name` LIKE ? AND `year` = ?';
$db_results = Dba::read($sql, array($name, $year));
$id_array = array();
while ($row = Dba::fetch_assoc($db_results)) {
- $key = 'null';
+ $key = 'null';
$id_array[$key] = $row['id'];
}
if (count($id_array)) {
- $id = array_shift($id_array);
+ $id = array_shift($id_array);
$exists = true;
}
}
@@ -316,10 +313,8 @@ class TVShow extends database_object implements library_item
return null;
}
- $sql = 'INSERT INTO `tvshow` (`name`, `prefix`, `year`) ' .
- 'VALUES(?, ?, ?)';
-
- $db_results = Dba::write($sql, array($name, $prefix, $year));
+ $sql = 'INSERT INTO `tvshow` (`name`, `prefix`, `year`, `summary`) VALUES(?, ?, ?, ?)';
+ $db_results = Dba::write($sql, array($name, $prefix, $year, $tvshow_summary));
if (!$db_results) {
return null;
}
@@ -327,7 +322,6 @@ class TVShow extends database_object implements library_item
self::$_mapcache[$name]['null'] = $id;
return $id;
-
}
/**
@@ -338,9 +332,9 @@ class TVShow extends database_object implements library_item
{
// Save our current ID
$current_id = $this->id;
- $name = isset($data['name']) ? $data['name'] : $this->name;
- $year = isset($data['year']) ? $data['year'] : $this->year;
- $summary = isset($data['summary']) ? $data['summary'] : $this->summary;
+ $name = isset($data['name']) ? $data['name'] : $this->name;
+ $year = isset($data['year']) ? $data['year'] : $this->year;
+ $summary = isset($data['summary']) ? $data['summary'] : $this->summary;
// Check if name is different than current name
if ($this->name != $name || $this->year != $year) {
@@ -360,15 +354,15 @@ class TVShow extends database_object implements library_item
}
$trimmed = Catalog::trim_prefix(trim($name));
- $name = $trimmed['string'];
- $prefix = $trimmed['prefix'];
+ $name = $trimmed['string'];
+ $prefix = $trimmed['prefix'];
$sql = 'UPDATE `tvshow` SET `name` = ?, `prefix` = ?, `year` = ?, `summary` = ? WHERE `id` = ?';
Dba::write($sql, array($name, $prefix, $year, $summary, $current_id));
- $this->name = $name;
- $this->prefix = $prefix;
- $this->year = $year;
+ $this->name = $name;
+ $this->prefix = $prefix;
+ $this->year = $year;
$this->summary = $summary;
$override_childs = false;
@@ -386,7 +380,6 @@ class TVShow extends database_object implements library_item
}
return $current_id;
-
} // update
/**
@@ -412,29 +405,30 @@ class TVShow extends database_object implements library_item
public function remove_from_disk()
{
- $deleted = true;
+ $deleted = true;
$season_ids = $this->get_seasons();
foreach ($season_ids as $id) {
- $season = new TVShow_Season($id);
+ $season = new TVShow_Season($id);
$deleted = $season->remove_from_disk();
if (!$deleted) {
- debug_event('tvshow', 'Error when deleting the season `' . $id .'`.', 1);
+ debug_event('tvshow', 'Error when deleting the season `' . $id . '`.', 1);
break;
}
}
if ($deleted) {
- $sql = "DELETE FROM `tvshow` WHERE `id` = ?";
+ $sql = "DELETE FROM `tvshow` WHERE `id` = ?";
$deleted = Dba::write($sql, array($this->id));
if ($deleted) {
Art::gc('tvshow', $this->id);
Userflag::gc('tvshow', $this->id);
Rating::gc('tvshow', $this->id);
Shoutbox::gc('tvshow', $this->id);
+ Useractivity::gc('tvshow', $this->id);
}
}
return $deleted;
}
-
} // end of tvshow class
+
diff --git a/sources/lib/class/tvshow_episode.class.php b/sources/lib/class/tvshow_episode.class.php
index b89ec76..21fd341 100644
--- a/sources/lib/class/tvshow_episode.class.php
+++ b/sources/lib/class/tvshow_episode.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -48,7 +48,6 @@ class TVShow_Episode extends Video
}
return true;
-
}
/**
@@ -73,7 +72,7 @@ class TVShow_Episode extends Video
}
$tags = $data['genre'];
- $tvshow = TVShow::check($data['tvshow'], $data['year']);
+ $tvshow = TVShow::check($data['tvshow'], $data['year'], $data['tvshow_summary']);
if ($options['gather_art'] && $tvshow && $data['tvshow_art'] && !Art::has_db($tvshow, 'tvshow')) {
$art = new Art($tvshow, 'tvshow');
$art->insert_url($data['tvshow_art']);
@@ -96,7 +95,7 @@ class TVShow_Episode extends Video
$sdata = $data;
// Replace relation name with db ids
- $sdata['tvshow'] = $tvshow;
+ $sdata['tvshow'] = $tvshow;
$sdata['tvshow_season'] = $tvshow_season;
return self::create($sdata);
}
@@ -112,7 +111,6 @@ class TVShow_Episode extends Video
Dba::write($sql, array($data['id'], $data['original_name'], $data['tvshow_season'], $data['tvshow_episode'], $data['summary']));
return $data['id'];
-
}
/**
@@ -123,21 +121,20 @@ class TVShow_Episode extends Video
{
parent::update($data);
- $original_name = isset($data['original_name']) ? $data['original_name'] : $this->original_name;
- $tvshow_season = isset($data['tvshow_season']) ? $data['tvshow_season'] : $this->season;
+ $original_name = isset($data['original_name']) ? $data['original_name'] : $this->original_name;
+ $tvshow_season = isset($data['tvshow_season']) ? $data['tvshow_season'] : $this->season;
$tvshow_episode = isset($data['tvshow_episode']) ? $data['tvshow_episode'] : $this->episode_number;
- $summary = isset($data['summary']) ? $data['summary'] : $this->summary;
+ $summary = isset($data['summary']) ? $data['summary'] : $this->summary;
$sql = "UPDATE `tvshow_episode` SET `original_name` = ?, `season` = ?, `episode_number` = ?, `summary` = ? WHERE `id` = ?";
Dba::write($sql, array($original_name, $tvshow_season, $tvshow_episode, $summary, $this->id));
- $this->original_name = $original_name;
- $this->season = $tvshow_season;
+ $this->original_name = $original_name;
+ $this->season = $tvshow_season;
$this->episode_number = $tvshow_episode;
- $this->summary = $summary;
+ $this->summary = $summary;
return $this->id;
-
}
/**
@@ -151,16 +148,16 @@ class TVShow_Episode extends Video
$season = new TVShow_Season($this->season);
$season->format($details);
- $this->f_title = ($this->original_name ?: $this->f_title);
- $this->f_link = '' . $this->f_title . '';
- $this->f_season = $season->f_name;
+ $this->f_title = ($this->original_name ?: $this->f_title);
+ $this->f_link = '' . $this->f_title . '';
+ $this->f_season = $season->f_name;
$this->f_season_link = $season->f_link;
- $this->f_tvshow = $season->f_tvshow;
+ $this->f_tvshow = $season->f_tvshow;
$this->f_tvshow_link = $season->f_tvshow_link;
$this->f_file = $this->f_tvshow;
if ($this->episode_number) {
- $this->f_file .= ' - S'. sprintf('%02d', $season->season_number) . 'E'. sprintf('%02d', $this->episode_number);
+ $this->f_file .= ' - S' . sprintf('%02d', $season->season_number) . 'E' . sprintf('%02d', $this->episode_number);
}
$this->f_file .= ' - ' . $this->f_title;
$this->f_full_title = $this->f_file;
@@ -174,7 +171,7 @@ class TVShow_Episode extends Video
*/
public function get_keywords()
{
- $keywords = parent::get_keywords();
+ $keywords = parent::get_keywords();
$keywords['tvshow'] = array('important' => true,
'label' => T_('TV Show'),
'value' => $this->f_tvshow);
@@ -208,8 +205,9 @@ class TVShow_Episode extends Video
public function get_description()
{
- if (!empty($this->summary))
+ if (!empty($this->summary)) {
return $this->summary;
+ }
$season = new TVShow_Season($this->season);
return $season->get_description();
@@ -217,20 +215,22 @@ class TVShow_Episode extends Video
public function display_art($thumb = 2)
{
- $id = null;
+ $id = null;
$type = null;
if (Art::has_db($this->id, 'video')) {
- $id = $this->id;
+ $id = $this->id;
$type = 'video';
- } else if (Art::has_db($this->season, 'tvshow_season')) {
- $id = $this->season;
- $type = 'tvshow_season';
} else {
- $season = new TVShow_Season($this->season);
- if (Art::has_db($season->tvshow, 'tvshow')) {
- $id = $season->tvshow;
- $type = 'tvshow';
+ if (Art::has_db($this->season, 'tvshow_season')) {
+ $id = $this->season;
+ $type = 'tvshow_season';
+ } else {
+ $season = new TVShow_Season($this->season);
+ if (Art::has_db($season->tvshow, 'tvshow')) {
+ $id = $season->tvshow;
+ $type = 'tvshow';
+ }
}
}
@@ -246,7 +246,7 @@ class TVShow_Episode extends Video
{
$deleted = parent::remove_from_disk();
if ($deleted) {
- $sql = "DELETE FROM `tvshow_episode` WHERE `id` = ?";
+ $sql = "DELETE FROM `tvshow_episode` WHERE `id` = ?";
$deleted = Dba::write($sql, array($this->id));
}
diff --git a/sources/lib/class/tvshow_season.class.php b/sources/lib/class/tvshow_season.class.php
index cd6e41a..22ce4ed 100644
--- a/sources/lib/class/tvshow_season.class.php
+++ b/sources/lib/class/tvshow_season.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -46,7 +46,9 @@ class TVShow_Season extends database_object implements library_item
public function __construct($id='')
{
/* If they failed to pass in an id, just run for it */
- if (!$id) { return false; }
+ if (!$id) {
+ return false;
+ }
/* Get the information from the db */
$info = $this->get_info($id);
@@ -56,7 +58,6 @@ class TVShow_Season extends database_object implements library_item
} // foreach info
return true;
-
} //constructor
/**
@@ -95,7 +96,6 @@ class TVShow_Season extends database_object implements library_item
}
return $results;
-
} // get_episodes
/**
@@ -113,16 +113,15 @@ class TVShow_Season extends database_object implements library_item
"WHERE `tvshow_episode`.`season` = ?";
$db_results = Dba::read($sql, array($this->id));
- $row = Dba::fetch_assoc($db_results);
+ $row = Dba::fetch_assoc($db_results);
parent::add_to_cache('tvshow_extra',$this->id,$row);
}
/* Set Object Vars */
- $this->episodes = $row['episode_count'];
+ $this->episodes = $row['episode_count'];
$this->catalog_id = $row['catalog_id'];
return $row;
-
} // _get_extra_info
/**
@@ -135,10 +134,10 @@ class TVShow_Season extends database_object implements library_item
$tvshow = new TVShow($this->tvshow);
$tvshow->format($details);
- $this->f_tvshow = $tvshow->f_name;
+ $this->f_tvshow = $tvshow->f_name;
$this->f_tvshow_link = $tvshow->f_link;
- $this->link = AmpConfig::get('web_path') . '/tvshow_seasons.php?action=show&season=' . $this->id;
+ $this->link = AmpConfig::get('web_path') . '/tvshow_seasons.php?action=show&season=' . $this->id;
$this->f_link = '' . $this->f_name . '';
if ($details) {
@@ -150,7 +149,7 @@ class TVShow_Season extends database_object implements library_item
public function get_keywords()
{
- $keywords = array();
+ $keywords = array();
$keywords['tvshow'] = array('important' => true,
'label' => T_('TV Show'),
'value' => $this->f_tvshow);
@@ -230,15 +229,17 @@ class TVShow_Season extends database_object implements library_item
public function display_art($thumb = 2)
{
- $id = null;
+ $id = null;
$type = null;
if (Art::has_db($this->id, 'tvshow_season')) {
- $id = $this->id;
+ $id = $this->id;
$type = 'tvshow_season';
- } else if (Art::has_db($this->tvshow, 'tvshow')) {
- $id = $this->tvshow;
- $type = 'tvshow';
+ } else {
+ if (Art::has_db($this->tvshow, 'tvshow')) {
+ $id = $this->tvshow;
+ $type = 'tvshow';
+ }
}
if ($id !== null && $type !== null) {
@@ -259,21 +260,21 @@ class TVShow_Season extends database_object implements library_item
return self::$_mapcache[$name]['null'];
}
- $id = 0;
+ $id = 0;
$exists = false;
if (!$exists) {
- $sql = 'SELECT `id` FROM `tvshow_season` WHERE `tvshow` = ? AND `season_number` = ?';
+ $sql = 'SELECT `id` FROM `tvshow_season` WHERE `tvshow` = ? AND `season_number` = ?';
$db_results = Dba::read($sql, array($tvshow, $season_number));
$id_array = array();
while ($row = Dba::fetch_assoc($db_results)) {
- $key = 'null';
+ $key = 'null';
$id_array[$key] = $row['id'];
}
if (count($id_array)) {
- $id = array_shift($id_array);
+ $id = array_shift($id_array);
$exists = true;
}
}
@@ -298,7 +299,6 @@ class TVShow_Season extends database_object implements library_item
self::$_mapcache[$name]['null'] = $id;
return $id;
-
}
/**
@@ -315,25 +315,26 @@ class TVShow_Season extends database_object implements library_item
public function remove_from_disk()
{
- $deleted = true;
+ $deleted = true;
$video_ids = $this->get_episodes();
foreach ($video_ids as $id) {
- $video = Video::create_from_id($id);
+ $video = Video::create_from_id($id);
$deleted = $video->remove_from_disk();
if (!$deleted) {
- debug_event('tvshow_season', 'Error when deleting the video `' . $id .'`.', 1);
+ debug_event('tvshow_season', 'Error when deleting the video `' . $id . '`.', 1);
break;
}
}
if ($deleted) {
- $sql = "DELETE FROM `tvshow_season` WHERE `id` = ?";
+ $sql = "DELETE FROM `tvshow_season` WHERE `id` = ?";
$deleted = Dba::write($sql, array($this->id));
if ($deleted) {
Art::gc('tvshow_season', $this->id);
Userflag::gc('tvshow_season', $this->id);
Rating::gc('tvshow_season', $this->id);
Shoutbox::gc('tvshow_season', $this->id);
+ Useractivity::gc('tvshow_season', $this->id);
}
}
@@ -345,5 +346,5 @@ class TVShow_Season extends database_object implements library_item
$sql = "UPDATE `tvshow_season` SET `tvshow` = ? WHERE `id` = ?";
return Dba::write($sql, array($tvshow_id, $season_id));
}
-
} // end of tvshow_season class
+
diff --git a/sources/lib/class/ui.class.php b/sources/lib/class/ui.class.php
index 563db1a..f5d615f 100644
--- a/sources/lib/class/ui.class.php
+++ b/sources/lib/class/ui.class.php
@@ -2,22 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; version 2
- * of the License.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -34,6 +33,26 @@ class UI
return false;
}
+ /**
+ * find_template
+ *
+ * Return the path to the template file wanted. The file can be overwriten
+ * by the theme if it's not a php file, or if it is and if option
+ * allow_php_themes is set to true.
+ */
+ public static function find_template($template)
+ {
+ $path = AmpConfig::get('theme_path') . '/templates/' . $template;
+ $realpath = AmpConfig::get('prefix') . $path;
+ $extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
+ if (($extension != 'php' || AmpConfig::get('allow_php_themes'))
+ && file_exists($realpath) && is_file($realpath)) {
+ return $path;
+ } else {
+ return '/templates/' . $template;
+ }
+ }
+
/**
* access_denied
*
@@ -44,7 +63,7 @@ class UI
// Clear any buffered crap
ob_end_clean();
header("HTTP/1.1 403 $error");
- require_once AmpConfig::get('prefix') . '/templates/show_denied.inc.php';
+ require_once AmpConfig::get('prefix') . UI::find_template('show_denied.inc.php');
exit;
}
@@ -57,7 +76,7 @@ class UI
public static function ajax_include($template)
{
ob_start();
- require AmpConfig::get('prefix') . '/templates/' . $template;
+ require AmpConfig::get('prefix') . UI::find_template('') . $template;
$output = ob_get_contents();
ob_end_clean();
@@ -158,11 +177,11 @@ END;
}
switch ($pass) {
- case 1: $unit = 'kB'; break;
- case 2: $unit = 'MB'; break;
- case 3: $unit = 'GB'; break;
- case 4: $unit = 'TB'; break;
- case 5: $unit = 'PB'; break;
+ case 1: $unit = 'kB'; break;
+ case 2: $unit = 'MB'; break;
+ case 3: $unit = 'GB'; break;
+ case 4: $unit = 'TB'; break;
+ case 5: $unit = 'PB'; break;
default: $unit = 'B'; break;
}
@@ -178,7 +197,7 @@ END;
{
if (preg_match('/^([0-9]+) *([[:alpha:]]+)$/', $value, $matches)) {
$value = $matches[1];
- $unit = strtolower(substr($matches[2], 0, 1));
+ $unit = strtolower(substr($matches[2], 0, 1));
} else {
return $value;
}
@@ -210,7 +229,7 @@ END;
if (is_array($name)) {
$hover_name = $name[1];
- $name = $name[0];
+ $name = $name[0];
}
$title = $title ?: T_(ucfirst($name));
@@ -220,7 +239,7 @@ END;
$hover_url = self::_find_icon($hover_name);
}
if ($bUseSprite) {
- $tag = 'updateText('" . $field . "', '" . json_encode($value) ."');\n";
+ echo "\n";
} else {
echo " " . $value . "
\n";
}
@@ -371,4 +390,14 @@ END;
return AmpConfig::get('web_path') . AmpConfig::get('theme_path') . '/images/ampache.png';
}
}
+
+ public static function is_grid_view($type)
+ {
+ $isgv = true;
+ $cn = 'browse_' . $type . '_grid_view';
+ if (isset($_COOKIE[$cn])) {
+ $isgv = ($_COOKIE[$cn] == 'true');
+ }
+ return $isgv;
+ }
}
diff --git a/sources/lib/class/update.class.php b/sources/lib/class/update.class.php
index 688939a..e18355c 100644
--- a/sources/lib/class/update.class.php
+++ b/sources/lib/class/update.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -58,7 +58,7 @@ class Update
{
$version = "";
/* Make sure that update_info exits */
- $sql = "SHOW TABLES LIKE 'update_info'";
+ $sql = "SHOW TABLES LIKE 'update_info'";
$db_results = Dba::read($sql);
if (!Dba::dbh()) {
header("Location: test.php");
@@ -72,14 +72,13 @@ class Update
else {
// If we've found the update_info table, let's get the version from it
- $sql = "SELECT * FROM `update_info` WHERE `key`='db_version'";
+ $sql = "SELECT * FROM `update_info` WHERE `key`='db_version'";
$db_results = Dba::read($sql);
- $results = Dba::fetch_assoc($db_results);
- $version = $results['value'];
+ $results = Dba::fetch_assoc($db_results);
+ $version = $results['value'];
}
return $version;
-
} // get_version
/**
@@ -138,7 +137,7 @@ class Update
$version[] = array('version' => '340001','description' => $update_string);
$update_string = '- Added Offset Limit to Preferences and removed from user table.';
- $version[] = array('version' => '340002','description' => $update_string);
+ $version[] = array('version' => '340002','description' => $update_string);
$update_string = '- Moved Art from the Album table into album_data to improve performance. ' .
'- Made some minor changes to song table to reduce size of each row. ' .
@@ -164,7 +163,7 @@ class Update
$version[] = array('version' => '340006','description' => $update_string);
$update_string = '- Altered the session table, making value a LONGTEXT. ';
- $version[] = array('version' => '340007','description' => $update_string);
+ $version[] = array('version' => '340007','description' => $update_string);
$update_string = '- Modified Playlist_Data table to account for multiple object types. ' .
'- Verified previous updates, adjusting as needed. ' .
@@ -206,7 +205,7 @@ class Update
$version[] = array('version' => '340016','description'=>$update_string);
$update_string = '- Fix Tables for new Democratic Play methodology. ';
- $version[] = array('version' => '340017','description'=>$update_string);
+ $version[] = array('version' => '340017','description'=>$update_string);
$update_string = '- Modify the Tag tables so that they actually work. ' .
'- Alter the Prefix fields to allow for more prefixs. ';
@@ -227,10 +226,10 @@ class Update
$version[] = array('version'=>'350004','description'=>$update_string);
$update_string = "- Add table for Video files ";
- $version[] = array('version'=>'350005','description'=>$update_string);
+ $version[] = array('version'=>'350005','description'=>$update_string);
$update_string = "- Add data for Lyrics ";
- $version[] = array('version'=>'350006','description'=>$update_string);
+ $version[] = array('version'=>'350006','description'=>$update_string);
$update_string = '- Remove unused fields from catalog, playlist, playlist_data ' .
'- Add tables for dynamic playlists ' .
@@ -262,250 +261,283 @@ class Update
$version[] = array('version'=>'360003','description'=>$update_string);
$update_string = '- Add uniqueness constraint to ratings. ';
- $version[] = array('version' => '360004','description' => $update_string);
+ $version[] = array('version' => '360004','description' => $update_string);
$update_string = '- Modify tmp_browse to allow caching of multiple browses per session. ';
- $version[] = array('version' => '360005','description' => $update_string);
+ $version[] = array('version' => '360005','description' => $update_string);
$update_string = '- Add table for dynamic playlists. ';
- $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. ';
- $version[] = array('version' => '360008','description' => $update_string);
+ $version[] = array('version' => '360008','description' => $update_string);
$update_string = '- Allow long sessionids in tmp_playlist table. ';
- $version[] = array('version' => '360009', 'description' => $update_string);
+ $version[] = array('version' => '360009', 'description' => $update_string);
$update_string = '- Allow compound MBIDs in the artist table. ';
- $version[] = array('version' => '360010', 'description' => $update_string);
+ $version[] = array('version' => '360010', 'description' => $update_string);
$update_string = '- Add table to store stream session playlist. ';
- $version[] = array('version' => '360011', 'description' => $update_string);
+ $version[] = array('version' => '360011', 'description' => $update_string);
$update_string = '- Drop enum for the type field in session. ';
- $version[] = array('version' => '360012', 'description' => $update_string);
+ $version[] = array('version' => '360012', 'description' => $update_string);
$update_string = '- Update stream_playlist table to address performance issues. ';
- $version[] = array('version' => '360013', 'description' => $update_string);
+ $version[] = array('version' => '360013', 'description' => $update_string);
$update_string = '- Increase the length of sessionids again. ';
- $version[] = array('version' => '360014', 'description' => $update_string);
+ $version[] = array('version' => '360014', 'description' => $update_string);
$update_string = '- Add iframes parameter to preferences. ';
- $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. ';
- $version[] = array('version' => '360016', 'description' => $update_string);
+ $version[] = array('version' => '360016', 'description' => $update_string);
$update_string = '- Add user flags on objects. ';
- $version[] = array('version' => '360017', 'description' => $update_string);
+ $version[] = array('version' => '360017', 'description' => $update_string);
$update_string = '- Add album default sort value to preferences. ';
- $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. ';
- $version[] = array('version' => '360019', 'description' => $update_string);
+ $version[] = array('version' => '360019', 'description' => $update_string);
$update_string = '- Catalog types are plugins now. ';
- $version[] = array('version' => '360020', 'description' => $update_string);
+ $version[] = array('version' => '360020', 'description' => $update_string);
$update_string = '- Add insertion date on Now Playing and option to show the current song in page title for Web player. ';
- $version[] = array('version' => '360021', 'description' => $update_string);
+ $version[] = array('version' => '360021', 'description' => $update_string);
$update_string = '- Remove unused live_stream fields and add codec field. ';
- $version[] = array('version' => '360022', 'description' => $update_string);
+ $version[] = array('version' => '360022', 'description' => $update_string);
$update_string = '- Enable/Disable SubSonic and Plex backend. ';
- $version[] = array('version' => '360023', 'description' => $update_string);
+ $version[] = array('version' => '360023', 'description' => $update_string);
$update_string = '- Drop flagged table. ';
- $version[] = array('version' => '360024', 'description' => $update_string);
+ $version[] = array('version' => '360024', 'description' => $update_string);
$update_string = '- Add options to enable HTML5 / Flash on web players. ';
- $version[] = array('version' => '360025', 'description' => $update_string);
+ $version[] = array('version' => '360025', 'description' => $update_string);
$update_string = '- Added agent to `object_count` table. ';
- $version[] = array('version' => '360026','description' => $update_string);
+ $version[] = array('version' => '360026','description' => $update_string);
$update_string = '- Add option to allow/disallow to show personnal information to other users (now playing and recently played). ';
- $version[] = array('version' => '360027','description' => $update_string);
+ $version[] = array('version' => '360027','description' => $update_string);
- $update_string = '- Personnal information: allow/disallow to show in now playing. '.
- '- Personnal information: allow/disallow to show in recently played. '.
+ $update_string = '- Personnal information: allow/disallow to show in now playing. ' .
+ '- Personnal information: allow/disallow to show in recently played. ' .
'- Personnal information: allow/disallow to show time and/or agent in recently played. ';
$version[] = array('version' => '360028','description' => $update_string);
$update_string = '- Add new table to store wanted releases. ';
- $version[] = array('version' => '360029','description' => $update_string);
+ $version[] = array('version' => '360029','description' => $update_string);
$update_string = '- New table to store song previews. ';
- $version[] = array('version' => '360030','description' => $update_string);
+ $version[] = array('version' => '360030','description' => $update_string);
$update_string = '- Add option to fix header position on compatible themes. ';
- $version[] = array('version' => '360031','description' => $update_string);
+ $version[] = array('version' => '360031','description' => $update_string);
$update_string = '- Add check update automatically option. ';
- $version[] = array('version' => '360032','description' => $update_string);
+ $version[] = array('version' => '360032','description' => $update_string);
$update_string = '- Add song waveform as song data. ';
- $version[] = array('version' => '360033','description' => $update_string);
+ $version[] = array('version' => '360033','description' => $update_string);
$update_string = '- Add settings for confirmation when closing window and auto-pause between tabs. ';
- $version[] = array('version' => '360034','description' => $update_string);
+ $version[] = array('version' => '360034','description' => $update_string);
$update_string = '- Add beautiful stream url setting. ';
- $version[] = array('version' => '360035','description' => $update_string);
+ $version[] = array('version' => '360035','description' => $update_string);
$update_string = '- Remove unused parameters. ';
- $version[] = array('version' => '360036','description' => $update_string);
+ $version[] = array('version' => '360036','description' => $update_string);
$update_string = '- Add sharing features. ';
- $version[] = array('version' => '360037','description' => $update_string);
+ $version[] = array('version' => '360037','description' => $update_string);
$update_string = '- Add missing albums browse on missing artists. ';
- $version[] = array('version' => '360038','description' => $update_string);
+ $version[] = array('version' => '360038','description' => $update_string);
$update_string = '- Add website field on users. ';
- $version[] = array('version' => '360039','description' => $update_string);
+ $version[] = array('version' => '360039','description' => $update_string);
$update_string = '- Add channels. ';
- $version[] = array('version' => '360041','description' => $update_string);
+ $version[] = array('version' => '360041','description' => $update_string);
$update_string = '- Add broadcasts and player control. ';
- $version[] = array('version' => '360042','description' => $update_string);
+ $version[] = array('version' => '360042','description' => $update_string);
$update_string = '- Add slideshow on currently played artist preference. ';
- $version[] = array('version' => '360043','description' => $update_string);
+ $version[] = array('version' => '360043','description' => $update_string);
$update_string = '- Add artist description/recommendation external service data cache. ';
- $version[] = array('version' => '360044','description' => $update_string);
+ $version[] = array('version' => '360044','description' => $update_string);
$update_string = '- Set user field on playlists as optional. ';
- $version[] = array('version' => '360045','description' => $update_string);
+ $version[] = array('version' => '360045','description' => $update_string);
$update_string = '- Add broadcast web player by default preference. ';
- $version[] = array('version' => '360046','description' => $update_string);
+ $version[] = array('version' => '360046','description' => $update_string);
$update_string = '- Add apikey field on users. ';
- $version[] = array('version' => '360047','description' => $update_string);
+ $version[] = array('version' => '360047','description' => $update_string);
$update_string = '- Add concerts options. ';
- $version[] = array('version' => '360048','description' => $update_string);
+ $version[] = array('version' => '360048','description' => $update_string);
$update_string = '- Add album group multiple disks setting. ';
- $version[] = array('version' => '360049','description' => $update_string);
+ $version[] = array('version' => '360049','description' => $update_string);
$update_string = '- Add top menu setting. ';
- $version[] = array('version' => '360050','description' => $update_string);
+ $version[] = array('version' => '360050','description' => $update_string);
$update_string = '- Copy default .htaccess configurations. ';
- $version[] = array('version' => '360051','description' => $update_string);
+ $version[] = array('version' => '360051','description' => $update_string);
$update_string = '- Drop unused dynamic_playlist tables and add session id to votes. ';
- $version[] = array('version' => '370001','description' => $update_string);
+ $version[] = array('version' => '370001','description' => $update_string);
$update_string = '- Add tag persistent merge reference. ';
- $version[] = array('version' => '370002','description' => $update_string);
+ $version[] = array('version' => '370002','description' => $update_string);
$update_string = '- Add show/hide donate button preference. ';
- $version[] = array('version' => '370003','description' => $update_string);
+ $version[] = array('version' => '370003','description' => $update_string);
$update_string = '- Add license information and user\'s artist association. ';
- $version[] = array('version' => '370004','description' => $update_string);
+ $version[] = array('version' => '370004','description' => $update_string);
$update_string = '- Add new column album_artist into table song. ';
- $version[] = array('version' => '370005','description' => $update_string);
+ $version[] = array('version' => '370005','description' => $update_string);
$update_string = '- Add random and limit options to smart playlists. ';
- $version[] = array('version' => '370006','description' => $update_string);
+ $version[] = array('version' => '370006','description' => $update_string);
$update_string = '- Add DAAP backend preference. ';
- $version[] = array('version' => '370007','description' => $update_string);
+ $version[] = array('version' => '370007','description' => $update_string);
$update_string = '- Add UPnP backend preference. ';
- $version[] = array('version' => '370008','description' => $update_string);
+ $version[] = array('version' => '370008','description' => $update_string);
$update_string = '- Enhance video support with TVShows and Movies. ';
- $version[] = array('version' => '370009','description' => $update_string);
+ $version[] = array('version' => '370009','description' => $update_string);
$update_string = '- Add MusicBrainz Album Release Group identifier. ';
- $version[] = array('version' => '370010','description' => $update_string);
+ $version[] = array('version' => '370010','description' => $update_string);
$update_string = '- Add Prefix to TVShows and Movies. ';
- $version[] = array('version' => '370011','description' => $update_string);
+ $version[] = array('version' => '370011','description' => $update_string);
$update_string = '- Add metadata information to albums / songs / videos. ';
- $version[] = array('version' => '370012','description' => $update_string);
+ $version[] = array('version' => '370012','description' => $update_string);
$update_string = '- Replace iframe with ajax page load. ';
- $version[] = array('version' => '370013','description' => $update_string);
+ $version[] = array('version' => '370013','description' => $update_string);
$update_string = '- Modified release_date in video table to signed int. ';
- $version[] = array('version' => '370014','description' => $update_string);
+ $version[] = array('version' => '370014','description' => $update_string);
$update_string = '- Add session_remember table to store remember tokens. ';
- $version[] = array('version' => '370015','description' => $update_string);
+ $version[] = array('version' => '370015','description' => $update_string);
$update_string = '- Add limit of media count for direct play preference. ';
- $version[] = array('version' => '370016','description' => $update_string);
+ $version[] = array('version' => '370016','description' => $update_string);
$update_string = '- Add home display settings. ';
- $version[] = array('version' => '370017','description' => $update_string);
+ $version[] = array('version' => '370017','description' => $update_string);
$update_string = '- Enhance tag persistent merge reference. ';
- $version[] = array('version' => '370018','description' => $update_string);
+ $version[] = array('version' => '370018','description' => $update_string);
$update_string = '- Add album group order setting. ';
- $version[] = array('version' => '370019','description' => $update_string);
+ $version[] = array('version' => '370019','description' => $update_string);
$update_string = '- Add webplayer browser notification settings. ';
- $version[] = array('version' => '370020','description' => $update_string);
+ $version[] = array('version' => '370020','description' => $update_string);
$update_string = '- Add rating to playlists, tvshows and tvshows seasons. ';
- $version[] = array('version' => '370021','description' => $update_string);
+ $version[] = array('version' => '370021','description' => $update_string);
$update_string = '- Add users geolocation. ';
- $version[] = array('version' => '370022','description' => $update_string);
+ $version[] = array('version' => '370022','description' => $update_string);
$update_string = " - Add Aurora.js webplayer option. ";
- $version[] = array('version' => '370023','description' => $update_string);
+ $version[] = array('version' => '370023','description' => $update_string);
$update_string = " - Add count_type column to object_count table. ";
- $version[] = array('version' => '370024','description' => $update_string);
+ $version[] = array('version' => '370024','description' => $update_string);
$update_string = " - Add state and city fields to user table. ";
- $version[] = array('version' => '370025','description' => $update_string);
+ $version[] = array('version' => '370025','description' => $update_string);
$update_string = " - Add replay gain fields to song_data table. ";
- $version[] = array('version' => '370026','description' => $update_string);
+ $version[] = array('version' => '370026','description' => $update_string);
$update_string = " - Move column album_artist from table song to table album. ";
- $version[] = array('version' => '370027','description' => $update_string);
+ $version[] = array('version' => '370027','description' => $update_string);
$update_string = " - Add width and height in table image. ";
- $version[] = array('version' => '370028','description' => $update_string);
+ $version[] = array('version' => '370028','description' => $update_string);
$update_string = " - Set image column from image table as nullable. ";
- $version[] = array('version' => '370029','description' => $update_string);
+ $version[] = array('version' => '370029','description' => $update_string);
$update_string = " - Add an option to allow users to remove uploaded songs. ";
- $version[] = array('version' => '370030','description' => $update_string);
+ $version[] = array('version' => '370030','description' => $update_string);
$update_string = " - Add an option to customize login art, favicon and text footer. ";
- $version[] = array('version' => '370031','description' => $update_string);
+ $version[] = array('version' => '370031','description' => $update_string);
$update_string = " - Add WebDAV backend preference. ";
- $version[] = array('version' => '370032','description' => $update_string);
+ $version[] = array('version' => '370032','description' => $update_string);
$update_string = " - Add Label tables. ";
- $version[] = array('version' => '370033','description' => $update_string);
+ $version[] = array('version' => '370033','description' => $update_string);
$update_string = " - Add User messages and user follow tables. ";
- $version[] = array('version' => '370034','description' => $update_string);
+ $version[] = array('version' => '370034','description' => $update_string);
$update_string = " - Add option on user fullname to show/hide it publicly. ";
- $version[] = array('version' => '370035','description' => $update_string);
+ $version[] = array('version' => '370035','description' => $update_string);
+
+ $update_string = " - Add track number field to stream_playlist table. ";
+ $version[] = array('version' => '370036','description' => $update_string);
+
+ $update_string = " - Delete http_port preference (use ampache.cfg.php configuration instead). ";
+ $version[] = array('version' => '370037','description' => $update_string);
+ $update_string = " - Add theme color option. ";
+ $version[] = array('version' => '370038','description' => $update_string);
+
+ $update_string = " - Renamed false named sample_rate option name in preference table. ";
+ $version[] = array('version' => '370039','description' => $update_string);
+
+ $update_string = " - Add user_activity table. ";
+ $version[] = array('version' => '370040','description' => $update_string);
+
+ $update_string = "- Add basic metadata tables. ";
+ $version[] = array('version' => '370041', 'description' => $update_string);
+
+ $update_string = "- Add podcasts. ";
+ $version[] = array('version' => '380001', 'description' => $update_string);
+
+ $update_string = "- Add bookmarks. ";
+ $version[] = array('version' => '380002', 'description' => $update_string);
+
+ $update_string = "- Add unique constraint on tag_map table. ";
+ $version[] = array('version' => '380003', 'description' => $update_string);
+
+ $update_string = "- Add preference subcategory. ";
+ $version[] = array('version' => '380004', 'description' => $update_string);
+
+ $update_string = "- Add manual update flag on artist. ";
+ $version[] = array('version' => '380005', 'description' => $update_string);
+
return $version;
}
@@ -523,13 +555,16 @@ class Update
}
$update_needed = false;
- if (!defined('CLI')) { echo "
\n"; }
+ if (!defined('CLI')) {
+ echo "
\n";
+ }
foreach (self::$versions as $update) {
-
if ($update['version'] > $current_version) {
$update_needed = true;
- if (!defined('CLI')) { echo '
';
+ } // show
+} //end useractivity class
+
diff --git a/sources/lib/class/userflag.class.php b/sources/lib/class/userflag.class.php
index bb1535f..a276e3d 100644
--- a/sources/lib/class/userflag.class.php
+++ b/sources/lib/class/userflag.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -39,11 +39,10 @@ class Userflag extends database_object
*/
public function __construct($id, $type)
{
- $this->id = intval($id);
+ $this->id = intval($id);
$this->type = $type;
return true;
-
} // Constructor
/**
@@ -53,16 +52,18 @@ class Userflag extends database_object
*/
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 ($user_id === null) {
$user_id = $GLOBALS['user']->id;
}
$userflags = array();
$idlist = '(' . implode(',', $ids) . ')';
- $sql = "SELECT `object_id` FROM `user_flag` " .
+ $sql = "SELECT `object_id` FROM `user_flag` " .
"WHERE `user` = ? AND `object_id` IN $idlist " .
"AND `object_type` = ?";
$db_results = Dba::read($sql, array($user_id, $type));
@@ -81,7 +82,6 @@ class Userflag extends database_object
}
return true;
-
} // build_cache
/**
@@ -91,7 +91,7 @@ class Userflag extends database_object
*/
public static function gc($object_type = null, $object_id = null)
{
- $types = array('song', 'album', 'artist', 'video', 'tvshow', 'tvshow_season');
+ $types = array('song', 'album', 'artist', 'video', 'tvshow', 'tvshow_season', 'podcast', 'podcast_episode');
if ($object_type != null) {
if (in_array($object_type, $types)) {
@@ -109,7 +109,7 @@ class Userflag extends database_object
public function get_flag($user_id = null)
{
- if (is_null($user_id)) {
+ if ($user_id === null) {
$user_id = $GLOBALS['user']->id;
}
@@ -118,7 +118,7 @@ class Userflag extends database_object
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` = ?";
$db_results = Dba::read($sql, array($user_id, $this->id, $this->type));
@@ -129,7 +129,6 @@ class Userflag extends database_object
parent::add_to_cache($key, $this->id, $flagged);
return $flagged;
-
}
/**
@@ -139,7 +138,7 @@ class Userflag extends database_object
*/
public function set_flag($flagged, $user_id = null)
{
- if (is_null($user_id)) {
+ if ($user_id === null) {
$user_id = $GLOBALS['user']->id;
}
$user_id = intval($user_id);
@@ -157,13 +156,33 @@ class Userflag extends database_object
"(`object_id`, `object_type`, `user`, `date`) " .
"VALUES (?, ?, ?, ?)";
$params = array($this->id, $this->type, $user_id, time());
+
+ Useractivity::post_activity($user_id, 'userflag', $this->type, $this->id);
}
Dba::write($sql, $params);
parent::add_to_cache('userflag_' . $this->type . '_user' . $user_id, $this->id, $flagged);
- return true;
+ // Forward flag to last.fm and Libre.fm (song only)
+ if ($this->type == 'song') {
+ $user = new User($user_id);
+ $song = new Song($this->id);
+ if ($song) {
+ $song->format();
+ foreach (Plugin::get_plugins('save_mediaplay') as $plugin_name) {
+ try {
+ $plugin = new Plugin($plugin_name);
+ if ($plugin->load($user)) {
+ $plugin->_plugin->set_flag($song, $flagged);
+ }
+ } catch (Exception $e) {
+ debug_event('user.class.php', 'Stats plugin error: ' . $e->getMessage(), '1');
+ }
+ }
+ }
+ }
+ return true;
} // set_flag
/**
@@ -172,7 +191,7 @@ class Userflag extends database_object
*/
public static function get_latest_sql($type, $user_id=null)
{
- if (is_null($user_id)) {
+ if ($user_id === null) {
$user_id = $GLOBALS['user']->id;
}
$user_id = intval($user_id);
@@ -183,7 +202,7 @@ class Userflag extends database_object
$sql .= " LEFT JOIN `user` ON `user`.`id` = `user_flag`.`user`" .
" WHERE `user`.`access` >= 50";
}
- if (!is_null($type)) {
+ if ($type !== null) {
if ($user_id <= 0) {
$sql .= " AND";
} else {
@@ -225,7 +244,7 @@ class Userflag extends database_object
$results = array();
while ($row = Dba::fetch_assoc($db_results)) {
- if (is_null($type)) {
+ if ($type === null) {
$results[] = $row;
} else {
$results[] = $row['id'];
@@ -233,7 +252,6 @@ class Userflag extends database_object
}
return $results;
-
} // get_latest
/**
@@ -244,11 +262,12 @@ class Userflag extends database_object
public static function show($object_id, $type)
{
// If user flags aren't enabled don't do anything
- if (!AmpConfig::get('userflags')) { return false; }
+ if (!AmpConfig::get('userflags')) {
+ return false;
+ }
$userflag = new Userflag($object_id, $type);
- require AmpConfig::get('prefix') . '/templates/show_object_userflag.inc.php';
-
+ require AmpConfig::get('prefix') . UI::find_template('show_object_userflag.inc.php');
} // show
-
} //end rating class
+
diff --git a/sources/lib/class/vainfo.class.php b/sources/lib/class/vainfo.class.php
index 2f5d361..9ac9c43 100644
--- a/sources/lib/class/vainfo.class.php
+++ b/sources/lib/class/vainfo.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -28,23 +28,23 @@
*/
class vainfo
{
- public $encoding = '';
+ public $encoding = '';
public $encoding_id3v1 = '';
public $encoding_id3v2 = '';
public $filename = '';
- public $type = '';
- public $tags = array();
+ public $type = '';
+ public $tags = array();
public $islocal;
public $gather_types = array();
- protected $_raw = array();
- protected $_getID3 = null;
+ protected $_raw = array();
+ protected $_getID3 = null;
protected $_forcedSize = 0;
protected $_file_encoding = '';
- protected $_file_pattern = '';
- protected $_dir_pattern = '';
+ protected $_file_pattern = '';
+ protected $_dir_pattern = '';
private $_pathinfo;
private $_broken = false;
@@ -58,10 +58,10 @@ class vainfo
*/
public function __construct($file, $gather_types = array(), $encoding = null, $encoding_id3v1 = null, $encoding_id3v2 = null, $dir_pattern = '', $file_pattern ='', $islocal = true)
{
- $this->islocal = $islocal;
- $this->filename = $file;
+ $this->islocal = $islocal;
+ $this->filename = $file;
$this->gather_types = $gather_types;
- $this->encoding = $encoding ?: AmpConfig::get('site_charset');
+ $this->encoding = $encoding ?: AmpConfig::get('site_charset');
/* These are needed for the filename mojo */
$this->_file_pattern = $file_pattern;
@@ -80,14 +80,14 @@ class vainfo
// Initialize getID3 engine
$this->_getID3 = new getID3();
- $this->_getID3->option_md5_data = false;
+ $this->_getID3->option_md5_data = false;
$this->_getID3->option_md5_data_source = false;
- $this->_getID3->option_tags_html = false;
- $this->_getID3->option_extra_info = true;
- $this->_getID3->option_tag_lyrics3 = true;
- $this->_getID3->option_tags_process = true;
- $this->_getID3->option_tag_apetag = true;
- $this->_getID3->encoding = $this->encoding;
+ $this->_getID3->option_tags_html = false;
+ $this->_getID3->option_extra_info = true;
+ $this->_getID3->option_tag_lyrics3 = true;
+ $this->_getID3->option_tags_process = true;
+ $this->_getID3->option_tag_apetag = true;
+ $this->_getID3->encoding = $this->encoding;
// get id3tag encoding (try to work around off-spec id3v1 tags)
try {
@@ -131,7 +131,7 @@ class vainfo
}
}
- $this->encoding_id3v2 = self::_detect_encoding($tags, $mb_order);
+ $this->encoding_id3v2 = self::_detect_encoding($tags, $mb_order);
$this->_getID3->encoding = $this->encoding_id3v2;
}
@@ -152,31 +152,35 @@ class vainfo
*/
private static function _detect_encoding($tags, $mb_order)
{
- if (!function_exists('mb_detect_encoding'))
+ if (!function_exists('mb_detect_encoding')) {
return 'ISO-8859-1';
+ }
$encodings = array();
if (is_array($tags)) {
foreach ($tags as $tag) {
- if (is_array($tag))
+ if (is_array($tag)) {
$tag = implode(" ", $tag);
+ }
$enc = mb_detect_encoding($tag, $mb_order, true);
- if ($enc != false)
+ if ($enc != false) {
$encodings[$enc]++;
+ }
}
} else {
$enc = mb_detect_encoding($tags, $mb_order, true);
- if ($enc != false)
+ if ($enc != false) {
$encodings[$enc]++;
+ }
}
//!!debug_event('vainfo', 'encoding detection: ' . json_encode($encodings), 5);
- $high = 0;
+ $high = 0;
$encoding = 'ISO-8859-1';
foreach ($encodings as $key => $value) {
if ($value > $high) {
$encoding = $key;
- $high = $value;
+ $high = $value;
}
}
@@ -236,14 +240,14 @@ class vainfo
$this->read_id3();
if (isset($this->_raw['tags']['id3v2'])) {
getid3_lib::IncludeDependency(GETID3_INCLUDEPATH . 'write.php', __FILE__, true);
- $tagWriter = new getid3_writetags();
+ $tagWriter = new getid3_writetags();
$tagWriter->filename = $this->filename;
//'id3v2.4' doesn't saves the year;
- $tagWriter->tagformats = array('id3v1', 'id3v2.3');
- $tagWriter->overwrite_tags = true;
+ $tagWriter->tagformats = array('id3v1', 'id3v2.3');
+ $tagWriter->overwrite_tags = true;
$tagWriter->remove_other_tags = true;
- $tagWriter->tag_encoding = 'UTF-8';
- $TagData = $this->_raw['tags']['id3v2'];
+ $tagWriter->tag_encoding = 'UTF-8';
+ $TagData = $this->_raw['tags']['id3v2'];
// Foreach what we've got
foreach ($data as $key=>$value) {
@@ -253,10 +257,10 @@ class vainfo
}
if (isset($data['APIC'])) {
- $TagData['attached_picture'][0]['data'] = $data['APIC']['data'];
+ $TagData['attached_picture'][0]['data'] = $data['APIC']['data'];
$TagData['attached_picture'][0]['picturetypeid'] = '3';
- $TagData['attached_picture'][0]['description'] = 'Cover';
- $TagData['attached_picture'][0]['mime'] = $data['APIC']['mime'];
+ $TagData['attached_picture'][0]['description'] = 'Cover';
+ $TagData['attached_picture'][0]['mime'] = $data['APIC']['mime'];
}
$tagWriter->tag_data = $TagData;
@@ -341,20 +345,20 @@ class vainfo
foreach ($keys as $key) {
$tags = $results[$key];
- $info['file'] = $info['file'] ?: $tags['file'];
+ $info['file'] = $info['file'] ?: $tags['file'];
$info['bitrate'] = $info['bitrate'] ?: intval($tags['bitrate']);
- $info['rate'] = $info['rate'] ?: intval($tags['rate']);
- $info['mode'] = $info['mode'] ?: $tags['mode'];
- $info['size'] = $info['size'] ?: $tags['size'];
- $info['mime'] = $info['mime'] ?: $tags['mime'];
+ $info['rate'] = $info['rate'] ?: intval($tags['rate']);
+ $info['mode'] = $info['mode'] ?: $tags['mode'];
+ // size will be added later, because of conflicts between real file size and getID3 reported filesize
+ $info['mime'] = $info['mime'] ?: $tags['mime'];
$info['encoding'] = $info['encoding'] ?: $tags['encoding'];
- $info['rating'] = $info['rating'] ?: $tags['rating'];
- $info['time'] = $info['time'] ?: intval($tags['time']);
+ $info['rating'] = $info['rating'] ?: $tags['rating'];
+ $info['time'] = $info['time'] ?: intval($tags['time']);
$info['channels'] = $info['channels'] ?: $tags['channels'];
// This because video title are almost always bad...
$info['original_name'] = $info['original_name'] ?: stripslashes(trim($tags['original_name']));
- $info['title'] = $info['title'] ?: stripslashes(trim($tags['title']));
+ $info['title'] = $info['title'] ?: stripslashes(trim($tags['title']));
$info['year'] = $info['year'] ?: intval($tags['year']);
@@ -362,26 +366,26 @@ class vainfo
$info['totaldisks'] = $info['totaldisks'] ?: intval($tags['totaldisks']);
- $info['artist'] = $info['artist'] ?: trim($tags['artist']);
+ $info['artist'] = $info['artist'] ?: trim($tags['artist']);
$info['albumartist'] = $info['albumartist'] ?: trim($tags['albumartist']);
$info['album'] = $info['album'] ?: trim($tags['album']);
- $info['band'] = $info['band'] ?: trim($tags['band']);
- $info['composer'] = $info['composer'] ?: trim($tags['composer']);
+ $info['band'] = $info['band'] ?: trim($tags['band']);
+ $info['composer'] = $info['composer'] ?: trim($tags['composer']);
$info['publisher'] = $info['publisher'] ?: trim($tags['publisher']);
$info['genre'] = self::clean_array_tag('genre', $info, $tags);
- $info['mb_trackid'] = $info['mb_trackid'] ?: trim($tags['mb_trackid']);
- $info['mb_albumid'] = $info['mb_albumid'] ?: trim($tags['mb_albumid']);
+ $info['mb_trackid'] = $info['mb_trackid'] ?: trim($tags['mb_trackid']);
+ $info['mb_albumid'] = $info['mb_albumid'] ?: trim($tags['mb_albumid']);
$info['mb_albumid_group'] = $info['mb_albumid_group'] ?: trim($tags['mb_albumid_group']);
- $info['mb_artistid'] = $info['mb_artistid'] ?: trim($tags['mb_artistid']);
+ $info['mb_artistid'] = $info['mb_artistid'] ?: trim($tags['mb_artistid']);
$info['mb_albumartistid'] = $info['mb_albumartistid'] ?: trim($tags['mb_albumartistid']);
- $info['release_type'] = $info['release_type'] ?: trim($tags['release_type']);
+ $info['release_type'] = $info['release_type'] ?: trim($tags['release_type']);
$info['language'] = $info['language'] ?: trim($tags['language']);
- $info['comment'] = $info['comment'] ?: trim($tags['comment']);
+ $info['comment'] = $info['comment'] ?: trim($tags['comment']);
$info['lyrics'] = $info['lyrics']
?: strip_tags(nl2br($tags['lyrics']), " ");
@@ -390,34 +394,54 @@ class vainfo
$info['replaygain_album_gain'] = $info['replaygain_album_gain'] ?: floatval($tags['replaygain_album_gain']);
$info['replaygain_album_peak'] = $info['replaygain_album_peak'] ?: floatval($tags['replaygain_album_peak']);
- $info['track'] = $info['track'] ?: intval($tags['track']);
- $info['resolution_x'] = $info['resolution_x'] ?: intval($tags['resolution_x']);
- $info['resolution_y'] = $info['resolution_y'] ?: intval($tags['resolution_y']);
- $info['display_x'] = $info['display_x'] ?: intval($tags['display_x']);
- $info['display_y'] = $info['display_y'] ?: intval($tags['display_y']);
- $info['frame_rate'] = $info['frame_rate'] ?: floatval($tags['frame_rate']);
+ $info['track'] = $info['track'] ?: intval($tags['track']);
+ $info['resolution_x'] = $info['resolution_x'] ?: intval($tags['resolution_x']);
+ $info['resolution_y'] = $info['resolution_y'] ?: intval($tags['resolution_y']);
+ $info['display_x'] = $info['display_x'] ?: intval($tags['display_x']);
+ $info['display_y'] = $info['display_y'] ?: intval($tags['display_y']);
+ $info['frame_rate'] = $info['frame_rate'] ?: floatval($tags['frame_rate']);
$info['video_bitrate'] = $info['video_bitrate'] ?: intval($tags['video_bitrate']);
- $info['audio_codec'] = $info['audio_codec'] ?: trim($tags['audio_codec']);
- $info['video_codec'] = $info['video_codec'] ?: trim($tags['video_codec']);
- $info['description'] = $info['description'] ?: trim($tags['description']);
+ $info['audio_codec'] = $info['audio_codec'] ?: trim($tags['audio_codec']);
+ $info['video_codec'] = $info['video_codec'] ?: trim($tags['video_codec']);
+ $info['description'] = $info['description'] ?: trim($tags['description']);
- $info['tvshow'] = $info['tvshow'] ?: trim($tags['tvshow']);
- $info['tvshow_year'] = $info['tvshow_year'] ?: trim($tags['tvshow_year']);
- $info['tvshow_season'] = $info['tvshow_season'] ?: trim($tags['tvshow_season']);
+ $info['tvshow'] = $info['tvshow'] ?: trim($tags['tvshow']);
+ $info['tvshow_year'] = $info['tvshow_year'] ?: trim($tags['tvshow_year']);
+ $info['tvshow_season'] = $info['tvshow_season'] ?: trim($tags['tvshow_season']);
$info['tvshow_episode'] = $info['tvshow_episode'] ?: trim($tags['tvshow_episode']);
- $info['release_date'] = $info['release_date'] ?: trim($tags['release_date']);
-
- $info['tvshow_art'] = $info['tvshow_art'] ?: trim($tags['tvshow_art']);
+ $info['release_date'] = $info['release_date'] ?: trim($tags['release_date']);
+ $info['summary'] = $info['summary'] ?: trim($tags['summary']);
+ $info['tvshow_summary'] = $info['tvshow_summary'] ?: trim($tags['tvshow_summary']);
+
+ $info['tvshow_art'] = $info['tvshow_art'] ?: trim($tags['tvshow_art']);
$info['tvshow_season_art'] = $info['tvshow_season_art'] ?: trim($tags['tvshow_season_art']);
- $info['art'] = $info['art'] ?: trim($tags['art']);
+ $info['art'] = $info['art'] ?: trim($tags['art']);
+
+ if (AmpConfig::get('enable_custom_metadata') && is_array($tags)) {
+ // Add rest of the tags without typecast to the array
+ foreach ($tags as $tag => $value) {
+ if (!isset($info[$tag]) && !is_array($value)) {
+ $info[$tag] = (!is_array($value)) ? trim($value) : $value;
+ }
+ }
+ }
}
-
+
// Some things set the disk number even though there aren't multiple
if ($info['totaldisks'] == 1 && $info['disk'] == 1) {
unset($info['disk']);
unset($info['totaldisks']);
}
+ // Determine the correct file size, do not get fooled by the size which may be returned by id3v2!
+ if (isset($results['general']['size'])) {
+ $size = $results['general']['size'];
+ } else {
+ $size = Core::get_filesize(Core::conv_lc_file($filename));
+ }
+
+ $info['size'] = $info['size'] ?: $size;
+
return $info;
}
@@ -536,7 +560,7 @@ class vainfo
$results['general'] = $this->_parse_general($this->_raw);
- $cleaned = self::clean_tag_info($results, self::get_tag_type($results, 'getid3_tag_order'), $this->filename);
+ $cleaned = self::clean_tag_info($results, self::get_tag_type($results, 'getid3_tag_order'), $this->filename);
$cleaned['raw'] = $results;
return $cleaned;
@@ -571,7 +595,7 @@ class vainfo
$plugin_names = Plugin::get_plugins('get_metadata');
foreach ($tag_order as $tag_source) {
if (in_array($tag_source, $plugin_names)) {
- $plugin = new Plugin($tag_source);
+ $plugin = new Plugin($tag_source);
$installed_version = Plugin::get_plugin_version($plugin->_plugin->name);
if ($installed_version) {
if ($plugin->load($GLOBALS['user'])) {
@@ -591,26 +615,31 @@ class vainfo
private function _parse_general($tags)
{
$parsed = array();
+
+ if ((in_array('movie', $this->gather_types)) || (in_array('tvshow', $this->gather_types))) {
+ $parsed['title'] = $this->formatVideoName(urldecode($this->_pathinfo['filename']));
+ } else {
+ $parsed['title'] = urldecode($this->_pathinfo['filename']);
+ }
- $parsed['title'] = urldecode($this->_pathinfo['filename']);
- $parsed['mode'] = $tags['audio']['bitrate_mode'];
+ $parsed['mode'] = $tags['audio']['bitrate_mode'];
if ($parsed['mode'] == 'con') {
$parsed['mode'] = 'cbr';
}
- $parsed['bitrate'] = $tags['audio']['bitrate'];
- $parsed['channels'] = intval($tags['audio']['channels']);
- $parsed['rate'] = intval($tags['audio']['sample_rate']);
- $parsed['size'] = $this->_forcedSize ?: $tags['filesize'];
- $parsed['encoding'] = $tags['encoding'];
- $parsed['mime'] = $tags['mime_type'];
- $parsed['time'] = ($this->_forcedSize ? ((($this->_forcedSize - $tags['avdataoffset']) * 8) / $tags['bitrate']) : $tags['playtime_seconds']);
- $parsed['audio_codec'] = $tags['audio']['dataformat'];
- $parsed['video_codec'] = $tags['video']['dataformat'];
- $parsed['resolution_x'] = $tags['video']['resolution_x'];
- $parsed['resolution_y'] = $tags['video']['resolution_y'];
- $parsed['display_x'] = $tags['video']['display_x'];
- $parsed['display_y'] = $tags['video']['display_y'];
- $parsed['frame_rate'] = $tags['video']['frame_rate'];
+ $parsed['bitrate'] = $tags['audio']['bitrate'];
+ $parsed['channels'] = intval($tags['audio']['channels']);
+ $parsed['rate'] = intval($tags['audio']['sample_rate']);
+ $parsed['size'] = $this->_forcedSize ?: $tags['filesize'];
+ $parsed['encoding'] = $tags['encoding'];
+ $parsed['mime'] = $tags['mime_type'];
+ $parsed['time'] = ($this->_forcedSize ? ((($this->_forcedSize - $tags['avdataoffset']) * 8) / $tags['bitrate']) : $tags['playtime_seconds']);
+ $parsed['audio_codec'] = $tags['audio']['dataformat'];
+ $parsed['video_codec'] = $tags['video']['dataformat'];
+ $parsed['resolution_x'] = $tags['video']['resolution_x'];
+ $parsed['resolution_y'] = $tags['video']['resolution_y'];
+ $parsed['display_x'] = $tags['video']['display_x'];
+ $parsed['display_y'] = $tags['video']['display_y'];
+ $parsed['frame_rate'] = $tags['video']['frame_rate'];
$parsed['video_bitrate'] = $tags['video']['bitrate'];
if (isset($tags['ape'])) {
@@ -745,8 +774,8 @@ class vainfo
$parsed['track'] = $data[0];
break;
case 'discnumber':
- $elements = explode('/', $data[0]);
- $parsed['disk'] = $elements[0];
+ $elements = explode('/', $data[0]);
+ $parsed['disk'] = $elements[0];
$parsed['totaldisks'] = $elements[1];
break;
case 'date':
@@ -817,13 +846,17 @@ class vainfo
$parsed['genre'] = $this->parseGenres($data);
break;
case 'part_of_a_set':
- $elements = explode('/', $data[0]);
- $parsed['disk'] = $elements[0];
+ $elements = explode('/', $data[0]);
+ $parsed['disk'] = $elements[0];
$parsed['totaldisks'] = $elements[1];
break;
case 'track_number':
$parsed['track'] = $data[0];
break;
+ case 'comment':
+ // First array key can be xFF\xFE in case of UTF-8, better to get it this way
+ $parsed['comment'] = reset($data);
+ break;
case 'comments':
$parsed['comment'] = $data[0];
break;
@@ -897,8 +930,13 @@ class vainfo
$parsed['rating'][$user->id] = $popm['rating'] / 255 * 5;
}
}
+ // Rating made by an unknow user, adding it to super user (id=-1)
+ else {
+ $parsed['rating'][-1] = $popm['rating'] / 255 * 5;
+ }
}
}
+
return $parsed;
}
@@ -956,7 +994,7 @@ class vainfo
$parsed['mb_artistid'] = $data[0];
break;
case 'MusicBrainz Album Type':
- $parsed['release_type'] = $data[0];
+ $parsed['release_type'] = $data[0];
break;
case 'track_number':
$parsed['track'] = $data[0];
@@ -984,55 +1022,140 @@ class vainfo
return $parsed;
}
-
/**
- * _parse_filename
- *
* This function uses the file and directory patterns to pull out extra tag
* information.
+ * parses TV show name variations:
+ * 1. title.[date].S#[#]E#[#].ext (Upper/lower case)
+ * 2. title.[date].#[#]X#[#].ext (both upper/lower case letters
+ * 3. title.[date].Season #[#] Episode #[#].ext
+ * 4. title.[date].###.ext (maximum of 9 seasons)
+ * parse directory path for name, season and episode numbers
+ * /TV shows/show name [(year)]/[season ]##/##.Episode.Title.ext
+ * parse movie names:
+ * title.[date].ext
+ * /movie title [(date)]/title.ext
*/
- private function _parse_filename($filename)
+ private function _parse_filename($filepath)
{
- $origin = $filename;
+ $origin = $filepath;
$results = array();
-
- if (in_array('music', $this->gather_types) || in_array('clip', $this->gather_types)) {
- // Correctly detect the slash we need to use here
- if (strpos($filename, '/') !== false) {
- $slash_type = '/';
- $slash_type_preg = $slash_type;
+ if (strpos($filepath, '/') !== false) {
+ $slash_type = '/';
+ $slash_type_preg = $slash_type;
+ } else {
+ $slash_type = "\\";
+ $slash_type_preg = $slash_type . $slash_type;
+ }
+ $file = pathinfo($filepath,PATHINFO_FILENAME);
+
+ if (in_array('tvshow', $this->gather_types)) {
+ $season = array();
+ $episode = array();
+ $tvyear = array();
+ $temp = array();
+ preg_match("~(?<=\(\[\<\{)[1|2][0-9]{3}|[1|2][0-9]{3}~", $filepath,$tvyear);
+ $results['year'] = !empty($tvyear) ? intval($tvyear[0]) : null;
+
+ if (preg_match("~[Ss](\d+)[Ee](\d+)~", $file, $seasonEpisode)) {
+ $temp = preg_split("~(((\.|_|\s)[Ss]\d+(\.|_)*[Ee]\d+))~",$file,2);
+ preg_match("~(?<=[Ss])\d+~", $file, $season);
+ preg_match("~(?<=[Ee])\d+~", $file, $episode);
} else {
- $slash_type = '\\';
- $slash_type_preg = $slash_type . $slash_type;
+ if (preg_match("~[\_\-\.\s](\d{1,2})[xX](\d{1,2})~", $file, $seasonEpisode)) {
+ $temp = preg_split("~[\.\_\s\-\_]\d+[xX]\d{2}[\.\s\-\_]*|$~",$file);
+ preg_match("~\d+(?=[Xx])~", $file, $season);
+ preg_match("~(?<=[Xx])\d+~", $file, $episode);
+ } else {
+ if (preg_match("~[S|s]eason[\_\-\.\s](\d+)[\.\-\s\_]?\s?[e|E]pisode[\s\-\.\_]?(\d+)[\.\s\-\_]?~", $file, $seasonEpisode)) {
+ $temp = preg_split("~[\.\s\-\_][S|s]eason[\s\-\.\_](\d+)[\.\s\-\_]?\s?[e|E]pisode[\s\-\.\_](\d+)([\s\-\.\_])*~",$file,3);
+ preg_match("~(?<=[Ss]eason[\.\s\-\_])\d+~", $file, $season);
+ preg_match("~(?<=[Ee]pisode[\.\s\-\_])\d+~", $file, $episode);
+ } else {
+ if (preg_match("~[\_\-\.\s](\d)(\d\d)[\_\-\.\s]*~", $file, $seasonEpisode)) {
+ $temp = preg_split("~[\.\s\-\_](\d)(\d\d)[\.\s\-\_]~",$file);
+ $season[0] = $seasonEpisode[1];
+ if (preg_match("~[\_\-\.\s](\d)(\d\d)[\_\-\.\s]~", $file, $seasonEpisode)) {
+ $temp = preg_split("~[\.\s\-\_](\d)(\d\d)[\.\s\-\_]~",$file);
+ $season[0] = $seasonEpisode[1];
+ $episode[0] = $seasonEpisode[2];
+ }
+ }
+ }
+ }
+ }
+
+ $results['tvshow_season'] = $season[0];
+ $results['tvshow_episode'] = $episode[0];
+ $results['tvshow'] = $this->formatVideoName($temp[0]);
+ $results['original_name'] = $this->formatVideoName($temp[1]);
+
+ // Try to identify the show information from parent folder
+ if (!$results['tvshow']) {
+ $folders = preg_split("~" . $slash_type . "~", $filepath, -1, PREG_SPLIT_NO_EMPTY);
+ if ($results['tvshow_season'] && $results['tvshow_episode']) {
+ // We have season and episode, we assume parent folder is the tvshow name
+ $filetitle = end($folders);
+ $results['tvshow'] = $this->formatVideoName($filetitle);
+ } else {
+ // Or we assume each parent folder contains one missing information
+ if (preg_match('/[\/\\\\]([^\/\\\\]*)[\/\\\\]Season (\d{1,2})[\/\\\\]((E|Ep|Episode)\s?(\d{1,2})[\/\\\\])?/i', $filepath, $matches)) {
+ if ($matches != null) {
+ $results['tvshow'] = $this->formatVideoName($matches[1]);
+ $results['tvshow_season'] = $matches[2];
+ if (isset($matches[5])) {
+ $results['tvshow_episode'] = $matches[5];
+ } else {
+ //match pattern like 10.episode name.mp4
+ if (preg_match("~^(\d\d)[\_\-\.\s]?(.*)~", $file, $matches)) {
+ $results['tvshow_episode'] = $matches[1];
+ $results['original_name'] = $this->formatVideoName($matches[2]);
+ } else {
+ //Fallback to match any 3-digit Season/Episode that fails the standard pattern above.
+ preg_match("~(\d)(\d\d)[\_\-\.\s]?~", $file, $matches);
+ $results['tvshow_episode'] = $matches[2];
+ }
+ }
+ }
+ }
+ }
}
+ $results['title'] = $results['tvshow'];
+ }
+
+ if (in_array('movie', $this->gather_types)) {
+ $results['original_name'] = $results['title'] = $this->formatVideoName($file);
+ }
+
+ if (in_array('music', $this->gather_types) || in_array('clip', $this->gather_types)) {
// Combine the patterns
$pattern = preg_quote($this->_dir_pattern) . $slash_type_preg . preg_quote($this->_file_pattern);
-
+
// Remove first left directories from filename to match pattern
$cntslash = substr_count($pattern, preg_quote($slash_type)) + 1;
- $filepart = explode($slash_type, $filename);
+ $filepart = explode($slash_type, $filepath);
if (count($filepart) > $cntslash) {
- $filename = implode($slash_type, array_slice($filepart, count($filepart) - $cntslash));
+ $filepath = implode($slash_type, array_slice($filepart, count($filepart) - $cntslash));
}
-
+
// Pull out the pattern codes into an array
preg_match_all('/\%\w/', $pattern, $elements);
-
+
// Mangle the pattern by turning the codes into regex captures
$pattern = preg_replace('/\%[Ty]/', '([0-9]+?)', $pattern);
$pattern = preg_replace('/\%\w/', '(.+?)', $pattern);
$pattern = str_replace('/', '\/', $pattern);
$pattern = str_replace(' ', '\s', $pattern);
$pattern = '/' . $pattern . '\..+$/';
-
+
// Pull out our actual matches
- preg_match($pattern, $filename, $matches);
+ preg_match($pattern, $filepath, $matches);
if ($matches != null) {
// The first element is the full match text
$matched = array_shift($matches);
- debug_event('vainfo', $pattern . ' matched ' . $matched . ' on ' . $filename, 5);
-
+ debug_event('vainfo', $pattern . ' matched ' . $matched . ' on ' . $filepath, 5);
+
// Iterate over what we found
foreach ($matches as $key => $value) {
$new_key = translate_pattern_code($elements['0'][$key]);
@@ -1041,162 +1164,34 @@ class vainfo
}
}
- $results['title'] = $results['title'] ?: basename($filename);
+ $results['title'] = $results['title'] ?: basename($filepath);
if ($this->islocal) {
$results['size'] = Core::get_filesize(Core::conv_lc_file($origin));
}
}
}
-
- if (in_array('tvshow', $this->gather_types)) {
- $pathinfo = pathinfo($filename);
- $filetitle = $pathinfo['filename'];
-
- $results = array_merge($results, $this->parseEpisodeName($filetitle));
- if (!$results['tvshow']) {
- // Try to identify the show information from parent folder
- $filetitle = basename($pathinfo['dirname']);
- $results = array_merge($results, $this->parseEpisodeName($filetitle));
-
- if (!$results['tvshow']) {
- if ($results['tvshow_season'] && $results['tvshow_episode']) {
- // We have season and episode, we assume parent folder is the tvshow name
- $pathinfo = pathinfo($pathinfo['dirname']);
- $filetitle = basename($pathinfo['dirname']);
- $results['tvshow'] = $this->fixSerieName($filetitle);
- } else {
- // Or we assume each parent folder contains one missing information
- if (preg_match('/[\/\\\\]([^\/\\\\]*)[\/\\\\]Season (\d{1,2})[\/\\\\]((E|Ep|Episode)\s?(\d{1,2})[\/\\\\])?/i', $filename, $matches)) {
- if ($matches != null) {
- $results['tvshow'] = $this->fixSerieName($matches[1]);
- $results['tvshow_season'] = $matches[2];
- if (isset($matches[5])) {
- $results['tvshow_episode'] = $matches[5];
- }
- }
- }
- }
- }
- }
- }
-
- if (in_array('movie', $this->gather_types)) {
- $pathinfo = pathinfo($filename);
- $filetitle = $pathinfo['filename'];
- $results['title'] = $this->fixVideoReleaseName($filetitle);
- if (!$results['title']) {
- // Try to identify the movie information from parent folder
- $filetitle = basename($pathinfo['dirname']);
- $results['title'] = $this->fixVideoReleaseName($filetitle);
- }
- }
-
return $results;
}
-
- private function parseEpisodeName($filetitle)
+
+ private function removeCommonAbbreviations($name)
{
- $patterns = array(
- '/(.*)s(\d\d)e(\d\d)(\D.*)/i',
- '/(.*)s(\d\d)(\D)(.*)/i',
- '/(.*)\D(\d{1,2})x(\d\d)(\D)(.*)/i',
- '/(.*)\D(\d{1,2})x(\d\d)$/i',
- '/(\D*)[\.|\-|_](\d)(\d\d)([\.|\-|_]\D.*)/i',
- '/(\D*)(\d)[^0-9](\d\d)(\D.*)/i'
- );
+ $abbr = explode(",",AmpConfig::get('common_abbr'));
+ $commonabbr = preg_replace("~\n~", '',$abbr);
+ $commonabbr[] = '[1|2][0-9]{3}'; //Remove release year
- $results = array();
- for ($i=0;$ifixSerieName($matches[1]);
- if (empty($name)) {
- continue;
- }
-
- $season = floatval($matches[2]);
- if ($season == 0) {
- continue;
- }
-
- $episode = floatval($matches[3]);
- $leftover = $matches[4];
-
- if ($episode == 0) {
- // Some malformed string
- $leftover = $filetitle;
- }
-
- $results['tvshow'] = $name;
- $results['tvshow_season'] = $season;
- $results['tvshow_episode'] = $episode;
- $results['title'] = $this->fixVideoReleaseName($leftover);
- break;
- }
- }
-
- return $results;
+ //scan for brackets, braces, etc and ignore case.
+ for ($i=0; $i< count($commonabbr);$i++) {
+ $commonabbr[$i] = "~\[*|\(*|\<*|\{*\b(?i)" . trim($commonabbr[$i]) . "\b\]*|\)*|\>*|\}*~";
+ }
+ $string = preg_replace($commonabbr,'',$name);
+ return $string;
+ }
+
+ private function formatVideoName($name)
+ {
+ return ucwords(trim($this->removeCommonAbbreviations(str_replace(['.','_','-'], ' ', $name), "\s\t\n\r\0\x0B\.\_\-")));
}
- private function fixSerieName($name)
- {
- $name = str_replace('_', ' ', $name);
- $name = str_replace('.', ' ', $name);
- $name = str_replace(' ', ' ', $name);
- $name = $this->removeStartingDashesAndSpaces($name);
- $name = $this->removeEndingDashesAndSpaces($name);
-
- return ucwords($name);
- }
-
- private function fixVideoReleaseName($name)
- {
- $commonabbr = array(
- 'divx', 'xvid', 'dvdrip', 'hdtv', 'lol', 'axxo', 'repack', 'xor',
- 'pdtv', 'real', 'vtv', 'caph', '2hd', 'proper', 'fqm', 'uncut',
- 'topaz', 'tvt', 'notv', 'fpn', 'fov', 'orenji', '0tv', 'omicron',
- 'dsr', 'ws', 'sys', 'crimson', 'wat', 'hiqt', 'internal', 'brrip',
- 'boheme', 'vost', 'vostfr', 'fastsub', 'addiction'
- );
- for ($i=0; $ifixSerieName($name);
- }
-
- private function removeStartingDashesAndSpaces($name)
- {
- if (empty($name)) {
- return $name;
- }
-
- while (strpos($name, ' ') === 0 || strpos($name, '-') === 0) {
- $name = preg_replace('/^ /', '', $name);
- $name = preg_replace('/^-/', '', $name);
- }
-
- return $name;
- }
-
- private function removeEndingDashesAndSpaces($name)
- {
- if (empty($name)) {
- return $name;
- }
-
- while (strrpos($name, ' ') === strlen($name) - 1 || strrpos($name, '-') === strlen($name) - 1) {
- $name = preg_replace('/ $/', '', $name);
- $name = preg_replace('/-$/', '', $name);
- }
-
- return $name;
- }
/**
* set_broken
@@ -1216,10 +1211,10 @@ class vainfo
$key = array_shift($order);
- $broken = array();
- $broken[$key] = array();
- $broken[$key]['title'] = '**BROKEN** ' . $this->filename;
- $broken[$key]['album'] = 'Unknown (Broken)';
+ $broken = array();
+ $broken[$key] = array();
+ $broken[$key]['title'] = '**BROKEN** ' . $this->filename;
+ $broken[$key]['album'] = 'Unknown (Broken)';
$broken[$key]['artist'] = 'Unknown (Broken)';
return $broken;
@@ -1238,7 +1233,7 @@ class vainfo
$delimiters = AmpConfig::get('additional_genre_delimiters');
if (isset($data) && is_array($data) && count($data) === 1 && isset($delimiters)) {
$pattern = '~[\s]?(' . $delimiters . ')[\s]?~';
- $genres = preg_split($pattern, reset($data));
+ $genres = preg_split($pattern, reset($data));
if ($genres === false) {
throw new Exception('Pattern given in additional_genre_delimiters is not functional. Please ensure is it a valid regex (delimiter ~).');
}
@@ -1248,3 +1243,4 @@ class vainfo
return $data;
}
} // end class vainfo
+
diff --git a/sources/lib/class/video.class.php b/sources/lib/class/video.class.php
index e7b1593..38cee76 100644
--- a/sources/lib/class/video.class.php
+++ b/sources/lib/class/video.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -184,21 +184,24 @@ class Video extends database_object implements media, library_item
* Constructor
* This pulls the information from the database and returns
* a constructed object
- * @param int $id
+ * @param int|null $id
*/
- public function __construct($id)
+ public function __construct($id = null)
{
+ if (!$id) {
+ return false;
+ }
+
// Load the data from the database
$info = $this->get_info($id, 'video');
foreach ($info as $key=>$value) {
$this->$key = $value;
}
- $data = pathinfo($this->file);
+ $data = pathinfo($this->file);
$this->type = strtolower($data['extension']);
return true;
-
} // Constructor
/**
@@ -210,7 +213,7 @@ class Video extends database_object implements media, library_item
{
$dtypes = self::get_derived_types();
foreach ($dtypes as $dtype) {
- $sql = "SELECT `id` FROM `" . strtolower($dtype) . "` WHERE `id` = ?";
+ $sql = "SELECT `id` FROM `" . strtolower($dtype) . "` WHERE `id` = ?";
$db_results = Dba::read($sql, array($video_id));
if ($results = Dba::fetch_assoc($db_results)) {
if ($results['id']) {
@@ -228,17 +231,18 @@ class Video extends database_object implements media, library_item
*/
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) . ')';
- $sql = "SELECT * FROM `video` WHERE `video`.`id` IN $idlist";
+ $sql = "SELECT * FROM `video` WHERE `video`.`id` IN $idlist";
$db_results = Dba::read($sql);
while ($row = Dba::fetch_assoc($db_results)) {
parent::add_to_cache('video',$row['id'],$row);
}
-
} // build_cache
/**
@@ -247,11 +251,11 @@ class Video extends database_object implements media, library_item
*/
public function format($details = true)
{
- $this->f_title = scrub_out($this->title);
+ $this->f_title = scrub_out($this->title);
$this->f_full_title = $this->f_title;
- $this->link = AmpConfig::get('web_path') . "/video.php?action=show_video&video_id=" . $this->id;
- $this->f_link = "link . "\" title=\"" . scrub_out($this->f_title) . "\"> " . scrub_out($this->f_title) . "";
- $this->f_codec = $this->video_codec . ' / ' . $this->audio_codec;
+ $this->link = AmpConfig::get('web_path') . "/video.php?action=show_video&video_id=" . $this->id;
+ $this->f_link = "link . "\" title=\"" . scrub_out($this->f_title) . "\"> " . scrub_out($this->f_title) . "";
+ $this->f_codec = $this->video_codec . ' / ' . $this->audio_codec;
if ($this->resolution_x || $this->resolution_y) {
$this->f_resolution = $this->resolution_x . 'x' . $this->resolution_y;
}
@@ -260,32 +264,31 @@ class Video extends database_object implements media, library_item
}
// Format the Bitrate
- $this->f_bitrate = intval($this->bitrate/1000) . "-" . strtoupper($this->mode);
+ $this->f_bitrate = intval($this->bitrate/1000) . "-" . strtoupper($this->mode);
$this->f_video_bitrate = (string) intval($this->video_bitrate/1000);
if ($this->frame_rate) {
$this->f_frame_rate = $this->frame_rate . ' fps';
}
// Format the Time
- $min = floor($this->time/60);
- $sec = sprintf("%02d", ($this->time%60));
- $this->f_time = $min . ":" . $sec;
- $hour = sprintf("%02d", floor($min/60));
- $min_h = sprintf("%02d", ($min%60));
+ $min = floor($this->time/60);
+ $sec = sprintf("%02d", ($this->time%60));
+ $this->f_time = $min . ":" . $sec;
+ $hour = sprintf("%02d", floor($min/60));
+ $min_h = sprintf("%02d", ($min%60));
$this->f_time_h = $hour . ":" . $min_h . ":" . $sec;
if ($details) {
// Get the top tags
- $this->tags = Tag::get_top_tags('video', $this->id);
+ $this->tags = Tag::get_top_tags('video', $this->id);
$this->f_tags = Tag::get_display($this->tags, true, 'video');
}
$this->f_length = floor($this->time/60) . ' ' . T_('minutes');
- $this->f_file = $this->f_title . '.' . $this->type;
+ $this->f_file = $this->f_title . '.' . $this->type;
if ($this->release_date) {
$this->f_release_date = date('Y-m-d', $this->release_date);
}
-
} // format
/**
@@ -294,7 +297,7 @@ class Video extends database_object implements media, library_item
*/
public function get_keywords()
{
- $keywords = array();
+ $keywords = array();
$keywords['title'] = array('important' => true,
'label' => T_('Title'),
'value' => $this->f_title);
@@ -474,8 +477,9 @@ class Video extends database_object implements media, library_item
{
$dtypes = self::get_derived_types();
foreach ($dtypes as $dtype) {
- if (strtolower($type) == strtolower($dtype))
+ if (strtolower($type) == strtolower($dtype)) {
return $type;
+ }
}
return 'Video';
@@ -542,7 +546,7 @@ class Video extends database_object implements media, library_item
$release_date = intval($data['release_date']);
// No release date, then release date = production year
if (!$release_date && $data['year']) {
- $release_date = strtotime($data['year'] . '01-01');
+ $release_date = strtotime(strval($data['year']) . '-01-01');
}
$tags = $data['genre'];
$channels = intval($data['channels']);
@@ -614,7 +618,7 @@ class Video extends database_object implements media, library_item
{
if (isset($data['release_date'])) {
$f_release_date = $data['release_date'];
- $release_date = strtotime($f_release_date);
+ $release_date = strtotime($f_release_date);
} else {
$release_date = $this->release_date;
}
@@ -627,13 +631,25 @@ class Video extends database_object implements media, library_item
Tag::update_tag_list($data['edit_tags'], 'video', $this->id, true);
}
- $this->title = $title;
+ $this->title = $title;
$this->release_date = $release_date;
return $this->id;
-
} // update
+ public static function update_video($video_id, Video $new_video)
+ {
+ $update_time = time();
+
+ $sql = "UPDATE `video` SET `title` = ?, `bitrate` = ?, " .
+ "`size` = ?, `time` = ?, `video_codec` = ?, `audio_codec` = ?, " .
+ "`resolution_x` = ?, `resolution_y` = ?, `release_date` = ?, `channels` = ?, " .
+ "`display_x` = ?, `display_y` = ?, `frame_rate` = ?, `video_bitrate` = ?, " .
+ "`update_time` = ? WHERE `id` = ?";
+
+ Dba::write($sql, array($new_video->title, $new_video->bitrate, $new_video->size, $new_video->time, $new_video->video_codec, $new_video->audio_codec, $new_video->resolution_x, $new_video->resolution_y, $new_video->release_date, $new_video->channels, $new_video->display_x, $new_video->display_y, $new_video->frame_rate, $new_video->video_bitrate, $update_time, $video_id));
+ }
+
/**
* Get release item art.
* @return array
@@ -654,7 +670,7 @@ class Video extends database_object implements media, library_item
public static function generate_preview($video_id, $overwrite = false)
{
if ($overwrite || !Art::has_db($video_id, 'video', 'preview')) {
- $artp = new Art($video_id, 'video', 'preview');
+ $artp = new Art($video_id, 'video', 'preview');
$video = new Video($video_id);
$image = Stream::get_image_preview($video);
$artp->insert($image, 'image/png');
@@ -676,7 +692,7 @@ class Video extends database_object implements media, library_item
$count = 1;
}
- $sql = "SELECT DISTINCT(`video`.`id`) FROM `video` ";
+ $sql = "SELECT DISTINCT(`video`.`id`) FROM `video` ";
$where = "WHERE `video`.`enabled` = '1' ";
if (AmpConfig::get('catalog_disable')) {
$sql .= "LEFT JOIN `catalog` ON `catalog`.`id` = `video`.`catalog` ";
@@ -715,9 +731,28 @@ class Video extends database_object implements media, library_item
Video::update_played(true, $this->id);
return true;
-
} // set_played
+ /**
+ * compare_video_information
+ * this compares the new ID3 tags of a file against
+ * the ones in the database to see if they have changed
+ * it returns false if nothing has changes, or the true
+ * if they have. Static because it doesn't need this
+ * @param \Video $video
+ * @param \Video $new_video
+ * @return array
+ */
+ public static function compare_video_information(Video $video, Video $new_video)
+ {
+ // Remove some stuff we don't care about
+ unset($video->catalog,$video->played,$video->enabled,$video->addition_time,$video->update_time,$video->type);
+ $string_array = array('title','tags');
+ $skip_array = array('id','tag_id','mime','object_cnt');
+
+ return Song::compare_media_information($video, $new_video, $string_array, $skip_array);
+ } // compare_video_information
+
/**
* get_subtitles
* Get existing subtitles list for this video
@@ -726,11 +761,11 @@ class Video extends database_object implements media, library_item
public function get_subtitles()
{
$subtitles = array();
- $pinfo = pathinfo($this->file);
- $filter = $pinfo['dirname'] . DIRECTORY_SEPARATOR . $pinfo['filename'] . '*.srt';
+ $pinfo = pathinfo($this->file);
+ $filter = $pinfo['dirname'] . DIRECTORY_SEPARATOR . $pinfo['filename'] . '*.srt';
foreach (glob($filter) as $srt) {
- $psrt = explode('.', $srt);
+ $psrt = explode('.', $srt);
$lang_code = '__';
$lang_name = T_("Unknown");
if (count($psrt) >= 2) {
@@ -955,7 +990,7 @@ class Video extends database_object implements media, library_item
{
$subtitle = '';
if ($lang_code == '__' || $this->get_language_name($lang_code)) {
- $pinfo = pathinfo($this->file);
+ $pinfo = pathinfo($this->file);
$subtitle = $pinfo['dirname'] . DIRECTORY_SEPARATOR . $pinfo['filename'];
if ($lang_code != '__') {
$subtitle .= '.' . $lang_code;
@@ -977,13 +1012,14 @@ class Video extends database_object implements media, library_item
$deleted = true;
}
if ($deleted === true) {
- $sql = "DELETE FROM `video` WHERE `id` = ?";
+ $sql = "DELETE FROM `video` WHERE `id` = ?";
$deleted = Dba::write($sql, array($this->id));
if ($deleted) {
Art::gc('video', $this->id);
Userflag::gc('video', $this->id);
Rating::gc('video', $this->id);
Shoutbox::gc('video', $this->id);
+ Useractivity::gc('video', $this->id);
}
} else {
debug_event('video', 'Cannot delete ' . $this->file . 'file. Please check permissions.', 1);
@@ -1001,7 +1037,6 @@ class Video extends database_object implements media, library_item
public static function update_played($new_played, $song_id)
{
self::_update_item('played', ($new_played ? 1 : 0),$song_id,'25');
-
} // update_played
/**
@@ -1019,16 +1054,19 @@ class Video extends database_object implements media, library_item
private static function _update_item($field, $value, $song_id, $level)
{
/* Check them Rights! */
- if (!Access::check('interface',$level)) { return false; }
+ if (!Access::check('interface',$level)) {
+ return false;
+ }
/* Can't update to blank */
- if (!strlen(trim($value))) { return false; }
+ if (!strlen(trim($value))) {
+ return false;
+ }
$sql = "UPDATE `video` SET `$field` = ? WHERE `id` = ?";
Dba::write($sql, array($value, $song_id));
return true;
-
} // _update_item
-
} // end Video class
+
diff --git a/sources/lib/class/wanted.class.php b/sources/lib/class/wanted.class.php
index 0fd0127..c68cbbc 100644
--- a/sources/lib/class/wanted.class.php
+++ b/sources/lib/class/wanted.class.php
@@ -2,26 +2,26 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
use MusicBrainz\MusicBrainz;
-use MusicBrainz\Clients\RequestsMbClient;
+use MusicBrainz\HttpAdapters\RequestsHttpAdapter;
use MusicBrainz\Filters\ArtistFilter;
class Wanted extends database_object
@@ -93,7 +93,9 @@ class Wanted extends database_object
*/
public function __construct($id=0)
{
- if (!$id) { return true; }
+ if (!$id) {
+ return true;
+ }
/* Get the information from the db */
$info = $this->get_info($id);
@@ -115,7 +117,7 @@ class Wanted extends database_object
*/
public static function get_missing_albums($artist, $mbid='')
{
- $mb = new MusicBrainz(new RequestsMbClient());
+ $mb = new MusicBrainz(new RequestsHttpAdapter());
$includes = array(
'release-groups'
);
@@ -128,7 +130,7 @@ class Wanted extends database_object
}
$owngroups = array();
- $wartist = array();
+ $wartist = array();
if ($artist) {
$albums = $artist->get_albums();
foreach ($albums as $id) {
@@ -138,9 +140,9 @@ class Wanted extends database_object
} else {
if (trim($album->mbid)) {
$malbum = $mb->lookup('release', $album->mbid, array('release-groups'));
- if ($malbum['release-group']) {
- if (!in_array($malbum['release-group']['id'], $owngroups)) {
- $owngroups[] = $malbum['release-group']['id'];
+ if ($malbum->{'release-group'}) {
+ if (!in_array($malbum->{'release-group'}->id, $owngroups)) {
+ $owngroups[] = $malbum->{'release-group'}->id;
}
}
}
@@ -148,51 +150,51 @@ class Wanted extends database_object
}
} else {
$wartist['mbid'] = $mbid;
- $wartist['name'] = $martist['name'];
+ $wartist['name'] = $martist->name;
parent::add_to_cache('missing_artist', $mbid, $wartist);
$wartist = self::get_missing_artist($mbid);
}
$results = array();
- foreach ($martist['release-groups'] as $group) {
- if (in_array(strtolower($group['primary-type']), $types)) {
+ foreach ($martist->{'release-groups'} as $group) {
+ if (in_array(strtolower($group->{'primary-type'}), $types)) {
$add = true;
- for ($i = 0; $i < count($group['secondary-types']) && $add; ++$i) {
- $add = in_array(strtolower($group['secondary-types'][$i]), $types);
+ for ($i = 0; $i < count($group->{'secondary-types'}) && $add; ++$i) {
+ $add = in_array(strtolower($group->{'secondary-types'}[$i]), $types);
}
if ($add) {
- if (!in_array($group['id'], $owngroups)) {
- $wantedid = self::get_wanted($group['id']);
- $wanted = new Wanted($wantedid);
+ if (!in_array($group->id, $owngroups)) {
+ $wantedid = self::get_wanted($group->id);
+ $wanted = new Wanted($wantedid);
if ($wanted->id) {
$wanted->format();
} else {
- $wanted->mbid = $group['id'];
+ $wanted->mbid = $group->id;
if ($artist) {
$wanted->artist = $artist->id;
} else {
$wanted->artist_mbid = $mbid;
}
- $wanted->name = $group['title'];
- if (!empty($group['first-release-date'])) {
- if (strlen($group['first-release-date']) == 4) {
- $wanted->year = $group['first-release-date'];
+ $wanted->name = $group->title;
+ if (!empty($group->{'first-release-date'})) {
+ if (strlen($group->{'first-release-date'}) == 4) {
+ $wanted->year = $group->{'first-release-date'};
} else {
- $wanted->year = date("Y", strtotime($group['first-release-date']));
+ $wanted->year = date("Y", strtotime($group->{'first-release-date'}));
}
}
$wanted->accepted = false;
- $wanted->link = AmpConfig::get('web_path') . "/albums.php?action=show_missing&mbid=" . $group['id'];
+ $wanted->link = AmpConfig::get('web_path') . "/albums.php?action=show_missing&mbid=" . $group->id;
if ($artist) {
$wanted->link .= "&artist=" . $wanted->artist;
} else {
$wanted->link .= "&artist_mbid=" . $mbid;
}
- $wanted->f_link = "link . "\" title=\"" . $wanted->name . "\">" . $wanted->name . "";
+ $wanted->f_link = "link . "\" title=\"" . $wanted->name . "\">" . $wanted->name . "";
$wanted->f_artist_link = $artist ? $artist->f_link : $wartist['link'];
- $wanted->f_user = $GLOBALS['user']->f_name;
+ $wanted->f_user = $GLOBALS['user']->f_name;
}
$results[] = $wanted;
}
@@ -215,7 +217,7 @@ class Wanted extends database_object
if (parent::is_cached('missing_artist', $mbid) ) {
$wartist = parent::get_from_cache('missing_artist', $mbid);
} else {
- $mb = new MusicBrainz(new RequestsMbClient());
+ $mb = new MusicBrainz(new RequestsHttpAdapter());
$wartist['mbid'] = $mbid;
$wartist['name'] = T_('Unknown Artist');
@@ -225,7 +227,7 @@ class Wanted extends database_object
return $wartist;
}
- $wartist['name'] = $martist['name'];
+ $wartist['name'] = $martist->name;
parent::add_to_cache('missing_artist', $mbid, $wartist);
}
@@ -239,9 +241,9 @@ class Wanted extends database_object
$args = array(
'artist' => $name
);
- $filter = new ArtistFilter($args);
- $mb = new MusicBrainz(new RequestsMbClient());
- $res = $mb->search($filter);
+ $filter = new ArtistFilter($args);
+ $mb = new MusicBrainz(new RequestsHttpAdapter());
+ $res = $mb->search($filter);
$wartists = array();
foreach ($res as $r) {
$wartists[] = array(
@@ -258,7 +260,7 @@ class Wanted extends database_object
*/
public static function get_accepted_wanted_count()
{
- $sql = "SELECT COUNT(`id`) AS `wanted_cnt` FROM `wanted` WHERE `accepted` = 1";
+ $sql = "SELECT COUNT(`id`) AS `wanted_cnt` FROM `wanted` WHERE `accepted` = 1";
$db_results = Dba::read($sql);
if ($row = Dba::fetch_assoc($db_results)) {
return $row['wanted_cnt'];
@@ -274,7 +276,7 @@ class Wanted extends database_object
*/
public static function get_wanted($mbid)
{
- $sql = "SELECT `id` FROM `wanted` WHERE `mbid` = ?";
+ $sql = "SELECT `id` FROM `wanted` WHERE `mbid` = ?";
$db_results = Dba::read($sql, array($mbid));
if ($row = Dba::fetch_assoc($db_results)) {
return $row['id'];
@@ -289,7 +291,7 @@ class Wanted extends database_object
*/
public static function delete_wanted($mbid)
{
- $sql = "DELETE FROM `wanted` WHERE `mbid` = ?";
+ $sql = "DELETE FROM `wanted` WHERE `mbid` = ?";
$params = array( $mbid );
if (!$GLOBALS['user']->has_access('75')) {
$sql .= " AND `user` = ?";
@@ -306,10 +308,10 @@ class Wanted extends database_object
public static function delete_wanted_release($mbid)
{
if (self::get_accepted_wanted_count() > 0) {
- $mb = new MusicBrainz(new RequestsMbClient());
+ $mb = new MusicBrainz(new RequestsHttpAdapter());
$malbum = $mb->lookup('release', $mbid, array('release-groups'));
- if ($malbum['release-group']) {
- self::delete_wanted($malbum['release-group']);
+ if ($malbum->{'release-group'}) {
+ self::delete_wanted($malbum->{'release-group'});
}
}
}
@@ -322,7 +324,7 @@ class Wanted extends database_object
*/
public static function delete_wanted_by_name($artist, $album_name, $year)
{
- $sql = "DELETE FROM `wanted` WHERE `artist` = ? AND `name` = ? AND `year` = ?";
+ $sql = "DELETE FROM `wanted` WHERE `artist` = ? AND `name` = ? AND `year` = ?";
$params = array( $artist, $album_name, $year );
if (!$GLOBALS['user']->has_access('75')) {
$sql .= " AND `user` = ?";
@@ -364,7 +366,7 @@ class Wanted extends database_object
$userid = $GLOBALS['user']->id;
}
- $sql = "SELECT `id` FROM `wanted` WHERE `mbid` = ? AND `user` = ?";
+ $sql = "SELECT `id` FROM `wanted` WHERE `mbid` = ? AND `user` = ?";
$db_results = Dba::read($sql, array($mbid, $userid));
if ($row = Dba::fetch_assoc($db_results)) {
@@ -372,7 +374,6 @@ class Wanted extends database_object
}
return false;
-
}
/**
@@ -385,14 +386,14 @@ class Wanted extends database_object
*/
public static function add_wanted($mbid, $artist, $artist_mbid, $name, $year)
{
- $sql = "INSERT INTO `wanted` (`user`, `artist`, `artist_mbid`, `mbid`, `name`, `year`, `date`, `accepted`) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
+ $sql = "INSERT INTO `wanted` (`user`, `artist`, `artist_mbid`, `mbid`, `name`, `year`, `date`, `accepted`) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
$accept = $GLOBALS['user']->has_access('75') ? true : AmpConfig::get('wanted_auto_accept');
$params = array($GLOBALS['user']->id, $artist, $artist_mbid, $mbid, $name, $year, time(), '0');
Dba::write($sql, $params);
if ($accept) {
$wantedid = Dba::insert_id();
- $wanted = new Wanted($wantedid);
+ $wanted = new Wanted($wantedid);
$wanted->accept();
database_object::remove_from_cache('wanted', $wantedid);
@@ -424,41 +425,41 @@ class Wanted extends database_object
*/
public function load_all($track_details = true)
{
- $mb = new MusicBrainz(new RequestsMbClient());
+ $mb = new MusicBrainz(new RequestsHttpAdapter());
$this->songs = array();
try {
$group = $mb->lookup('release-group', $this->mbid, array( 'releases' ));
// Set fresh data
- $this->name = $group['title'];
- $this->year = date("Y", strtotime($group['first-release-date']));
+ $this->name = $group->title;
+ $this->year = date("Y", strtotime($group->{'first-release-date'}));
// Load from database if already cached
$this->songs = Song_preview::get_song_previews($this->mbid);
- if (count($group['releases']) > 0) {
- $this->release_mbid = $group['releases'][0]['id'];
+ if (count($group->releases) > 0) {
+ $this->release_mbid = $group->releases[0]->id;
if ($track_details && count($this->songs) == 0) {
// Use the first release as reference for track content
$release = $mb->lookup('release', $this->release_mbid, array( 'recordings' ));
- foreach ($release['media'] as $media) {
- foreach ($media['tracks'] as $track) {
- $song = array();
- $song['disk'] = $media['position'];
- $song['track'] = $track['number'];
- $song['title'] = $track['title'];
- $song['mbid'] = $track['id'];
+ foreach ($release->media as $media) {
+ foreach ($media->tracks as $track) {
+ $song = array();
+ $song['disk'] = $media->position;
+ $song['track'] = $track->number;
+ $song['title'] = $track->title;
+ $song['mbid'] = $track->id;
if ($this->artist) {
$song['artist'] = $this->artist;
}
$song['artist_mbid'] = $this->artist_mbid;
- $song['session'] = session_id();
- $song['album_mbid'] = $this->mbid;
+ $song['session'] = session_id();
+ $song['album_mbid'] = $this->mbid;
if ($this->artist) {
- $artist = new Artist($this->artist);
+ $artist = new Artist($this->artist);
$artist_name = $artist->name;
} else {
- $wartist = Wanted::get_missing_artist($this->artist_mbid);
+ $wartist = Wanted::get_missing_artist($this->artist_mbid);
$artist_name = $wartist['name'];
}
@@ -466,9 +467,10 @@ class Wanted extends database_object
foreach (Plugin::get_plugins('get_song_preview') as $plugin_name) {
$plugin = new Plugin($plugin_name);
if ($plugin->load($GLOBALS['user'])) {
- $song['file'] = $plugin->_plugin->get_song_preview($track['id'], $artist_name, $track['title']);
- if ($song['file'] != null)
+ $song['file'] = $plugin->_plugin->get_song_preview($track->id, $artist_name, $track->title);
+ if ($song['file'] != null) {
break;
+ }
}
}
@@ -499,15 +501,14 @@ class Wanted extends database_object
$artist->format();
$this->f_artist_link = $artist->f_link;
} else {
- $wartist = Wanted::get_missing_artist($this->artist_mbid);
+ $wartist = Wanted::get_missing_artist($this->artist_mbid);
$this->f_artist_link = $wartist['link'];
}
- $this->link = AmpConfig::get('web_path') . "/albums.php?action=show_missing&mbid=" . $this->mbid . "&artist=" . $this->artist . "&artist_mbid=" . $this->artist_mbid . "\" title=\"" . $this->name;
+ $this->link = AmpConfig::get('web_path') . "/albums.php?action=show_missing&mbid=" . $this->mbid . "&artist=" . $this->artist . "&artist_mbid=" . $this->artist_mbid . "\" title=\"" . $this->name;
$this->f_link = "link . "\">" . $this->name . "";
- $user = new User($this->user);
+ $user = new User($this->user);
$user->format();
$this->f_user = $user->f_name;
-
}
/**
@@ -531,9 +532,9 @@ class Wanted extends database_object
*/
public static function get_wanted_list()
{
- $sql = self::get_wanted_list_sql();
+ $sql = self::get_wanted_list_sql();
$db_results = Dba::read($sql);
- $results = array();
+ $results = array();
while ($row = Dba::fetch_assoc($db_results)) {
$results[] = $row['id'];
@@ -541,5 +542,5 @@ class Wanted extends database_object
return $results;
}
-
} // end of recommendation class
+
diff --git a/sources/lib/class/waveform.class.php b/sources/lib/class/waveform.class.php
index bf0ac7f..a2b31e7 100644
--- a/sources/lib/class/waveform.class.php
+++ b/sources/lib/class/waveform.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -62,7 +62,6 @@ class Waveform
{
// Static
return false;
-
} // Constructor
/**
@@ -72,7 +71,7 @@ class Waveform
*/
public static function get($song_id)
{
- $song = new Song($song_id);
+ $song = new Song($song_id);
$waveform = null;
if ($song->id) {
@@ -81,9 +80,9 @@ class Waveform
if (!$waveform) {
$catalog = Catalog::create_from_id($song->catalog);
if ($catalog->get_type() == 'local') {
- $transcode_to = 'wav';
+ $transcode_to = 'wav';
$transcode_cfg = AmpConfig::get('transcode');
- $valid_types = $song->get_stream_types();
+ $valid_types = $song->get_stream_types();
if ($song->type != $transcode_to) {
$basedir = AmpConfig::get('tmp_dir_path');
@@ -98,7 +97,7 @@ class Waveform
}
$transcoder = Stream::start_transcode($song, $transcode_to);
- $fp = $transcoder['handle'];
+ $fp = $transcoder['handle'];
if (!is_resource($fp)) {
debug_event('waveform', "Failed to open " . $song->file . " for waveform.", 3);
return null;
@@ -161,7 +160,7 @@ class Waveform
hexdec(substr($input, 2, 2)),
hexdec(substr($input, 4, 2))
);
- }
+ }
/**
* Create waveform from song file.
@@ -171,22 +170,28 @@ class Waveform
protected static function create_waveform($filename)
{
if (!file_exists($filename)) {
+ debug_event('waveform', 'File ' . $filename . ' doesn\'t exists', 1);
+ return null;
+ }
+
+ if (!check_php_gd()) {
+ debug_event('waveform', 'GD extension must be loaded', 1);
return null;
}
- $detail = 5;
- $width = 400;
- $height = 32;
+ $detail = 5;
+ $width = 400;
+ $height = 32;
$foreground = AmpConfig::get('waveform_color') ?: '#FF0000';
$background = '';
- $draw_flat = true;
+ $draw_flat = true;
// generate foreground color
list($r, $g, $b) = self::html2rgb($foreground);
$handle = fopen($filename, "r");
// wav file header retrieval
- $heading = array();
+ $heading = array();
$heading[] = fread($handle, 4);
$heading[] = bin2hex(fread($handle, 4));
$heading[] = fread($handle, 4);
@@ -212,7 +217,7 @@ class Waveform
// start putting together the initial canvas
// $data_size = (size_of_file - header_bytes_read) / skipped_bytes + 1
- $data_size = floor((Core::get_filesize($filename) - 44) / ($ratio + $byte) + 1);
+ $data_size = floor((Core::get_filesize($filename) - 44) / ($ratio + $byte) + 1);
$data_point = 0;
// create original image width based on amount of detail
@@ -222,32 +227,35 @@ class Waveform
// fill background of image
if ($background == "") {
- // transparent background specified
+ // transparent background specified
imagesavealpha($img, true);
- $transparentColor = imagecolorallocatealpha($img, 0, 0, 0, 127);
- imagefill($img, 0, 0, $transparentColor);
+ $transparentColor = imagecolorallocatealpha($img, 0, 0, 0, 127);
+ imagefill($img, 0, 0, $transparentColor);
} else {
- list($br, $bg, $bb) = self::html2rgb($background);
- imagefilledrectangle($img, 0, 0, (int) ($data_size / $detail), $height, imagecolorallocate($img, $br, $bg, $bb));
- } while (!feof($handle) && $data_point < $data_size) {
+ list($br, $bg, $bb) = self::html2rgb($background);
+ imagefilledrectangle($img, 0, 0, (int) ($data_size / $detail), $height, imagecolorallocate($img, $br, $bg, $bb));
+ }
+ while (!feof($handle) && $data_point < $data_size) {
if ($data_point++ % $detail == 0) {
- $bytes = array();
+ $bytes = array();
// get number of bytes depending on bitrate
- for ($i = 0; $i < $byte; $i++)
- $bytes[$i] = fgetc($handle);
+ for ($i = 0; $i < $byte; $i++) {
+ $bytes[$i] = fgetc($handle);
+ }
- switch ($byte) {
+ switch ($byte) {
// get value for 8-bit wav
case 1:
$data = self::findValues($bytes[0], $bytes[1]);
break;
// get value for 16-bit wav
case 2:
- if(ord($bytes[1]) & 128)
- $temp = 0;
- else
- $temp = 128;
+ if (ord($bytes[1]) & 128) {
+ $temp = 0;
+ } else {
+ $temp = 128;
+ }
$temp = chr((ord($bytes[1]) & 127) + $temp);
$data = floor(self::findValues($bytes[0], $temp) / 256);
break;
@@ -265,8 +273,8 @@ class Waveform
$v = (int) ($data / 255 * $height);
// don't print flat values on the canvas if not necessary
- if (!($v / $height == 0.5 && !$draw_flat))
- // draw the line on the image using the $v value and centering it vertically on the canvas
+ if (!($v / $height == 0.5 && !$draw_flat)) {
+ // draw the line on the image using the $v value and centering it vertically on the canvas
imageline(
$img,
// x1
@@ -279,9 +287,9 @@ class Waveform
$height - ($height - $v),
imagecolorallocate($img, $r, $g, $b)
);
-
+ }
} else {
- // skip this one due to lack of detail
+ // skip this one due to lack of detail
fseek($handle, $ratio + $byte, SEEK_CUR);
}
}
@@ -322,5 +330,5 @@ class Waveform
$sql = "UPDATE `song_data` SET `waveform` = ? WHERE `song_id` = ?";
return Dba::write($sql, array($waveform, $song_id));
}
-
} // Waveform class
+
diff --git a/sources/lib/class/webdav_auth.class.php b/sources/lib/class/webdav_auth.class.php
index a5342b5..13b330f 100644
--- a/sources/lib/class/webdav_auth.class.php
+++ b/sources/lib/class/webdav_auth.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
diff --git a/sources/lib/class/webdav_catalog.class.php b/sources/lib/class/webdav_catalog.class.php
index bbabbce..307bad1 100644
--- a/sources/lib/class/webdav_catalog.class.php
+++ b/sources/lib/class/webdav_catalog.class.php
@@ -3,21 +3,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -43,7 +43,7 @@ class WebDAV_Catalog extends DAV\Collection
$children = array();
$catalogs = null;
if ($this->catalog_id > 0) {
- $catalogs = array();
+ $catalogs = array();
$catalogs[] = $this->catalog_id;
}
$artists = Catalog::get_artists($catalogs);
@@ -61,8 +61,9 @@ class WebDAV_Catalog extends DAV\Collection
debug_event('webdav', 'Found ' . count($matches) . ' childs.', 5);
// Always return first match
// Warning: this means that two items with the same name will not be supported for now
- if (count($matches) > 0)
+ if (count($matches) > 0) {
return WebDAV_Directory::getChildFromArray($matches[0]);
+ }
throw new DAV\Exception\NotFound('The artist with name: ' . $name . ' could not be found');
}
diff --git a/sources/lib/class/webdav_directory.class.php b/sources/lib/class/webdav_directory.class.php
index 0acfab4..20e8f3c 100644
--- a/sources/lib/class/webdav_directory.class.php
+++ b/sources/lib/class/webdav_directory.class.php
@@ -3,21 +3,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -43,7 +43,7 @@ class WebDAV_Directory extends DAV\Collection
{
debug_event('webdav', 'Directory getChildren', 5);
$children = array();
- $childs = $this->libitem->get_childrens();
+ $childs = $this->libitem->get_childrens();
foreach ($childs as $key => $child) {
if (is_string($key)) {
foreach ($child as $schild) {
@@ -61,18 +61,20 @@ class WebDAV_Directory extends DAV\Collection
// Clean song name
if (strtolower(get_class($this->libitem)) === "album") {
$splitname = explode('-', $name, 3);
- $name = trim($splitname[count($splitname) - 1]);
- $nameinfo = pathinfo($name);
- $name = $nameinfo['filename'];
+ $name = trim($splitname[count($splitname) - 1]);
+ $nameinfo = pathinfo($name);
+ $name = $nameinfo['filename'];
}
debug_event('webdav', 'Directory getChild: ' . $name, 5);
$matches = $this->libitem->search_childrens($name);
// Always return first match
// Warning: this means that two items with the same name will not be supported for now
- if (count($matches) > 0)
+ if (count($matches) > 0) {
return WebDAV_Directory::getChildFromArray($matches[0]);
+ }
- throw new DAV\Exception\NotFound('The child with name: ' . $name . ' could not be found');;
+ throw new DAV\Exception\NotFound('The child with name: ' . $name . ' could not be found');
+ ;
}
public static function getChildFromArray($array)
diff --git a/sources/lib/class/webdav_file.class.php b/sources/lib/class/webdav_file.class.php
index fff2962..45c0f3d 100644
--- a/sources/lib/class/webdav_file.class.php
+++ b/sources/lib/class/webdav_file.class.php
@@ -3,21 +3,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
diff --git a/sources/lib/class/webplayer.class.php b/sources/lib/class/webplayer.class.php
index 10e7be4..27344d0 100644
--- a/sources/lib/class/webplayer.class.php
+++ b/sources/lib/class/webplayer.class.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -60,18 +60,22 @@ class WebPlayer
{
$types = array('real' => 'mp3', 'player' => '');
- $media = null;
+ $media = null;
$urlinfo = Stream_URL::parse($item->url);
if ($urlinfo['id'] && Core::is_media($urlinfo['type'])) {
$media = new $urlinfo['type']($urlinfo['id']);
- } else if ($urlinfo['id'] && $urlinfo['type'] == 'song_preview') {
- $media = new Song_Preview($urlinfo['id']);
- } else if (isset($urlinfo['demo_id'])) {
- $democratic = new Democratic($urlinfo['demo_id']);
- if ($democratic->id) {
- $song_id = $democratic->get_next_object();
- if ($song_id) {
- $media = new Song($song_id);
+ } else {
+ if ($urlinfo['id'] && $urlinfo['type'] == 'song_preview') {
+ $media = new Song_Preview($urlinfo['id']);
+ } else {
+ if (isset($urlinfo['demo_id'])) {
+ $democratic = new Democratic($urlinfo['demo_id']);
+ if ($democratic->id) {
+ $song_id = $democratic->get_next_object();
+ if ($song_id) {
+ $media = new Song($song_id);
+ }
+ }
}
}
}
@@ -79,7 +83,7 @@ class WebPlayer
if ($media != null) {
$ftype = $media->type;
- $transcode = false;
+ $transcode = false;
$transcode_cfg = AmpConfig::get('transcode');
// Check transcode is required
$valid_types = Song::get_stream_types_for_type($ftype, 'webplayer');
@@ -87,12 +91,12 @@ class WebPlayer
if ($transcode_cfg == 'always' || ($transcode_cfg != 'never' && in_array('transcode', $valid_types))) {
// Transcode forced from client side
if (!empty($force_type) && AmpConfig::get('transcode_player_customize')) {
- debug_event("webplayer.class.php", "Forcing type to {".$force_type."}", 5);
+ debug_event("webplayer.class.php", "Forcing type to {" . $force_type . "}", 5);
// Transcode only if excepted type available
$transcode_settings = $media->get_transcode_settings($force_type, 'webplayer');
if ($transcode_settings) {
$types['real'] = $transcode_settings['format'];
- $transcode = true;
+ $transcode = true;
}
}
@@ -102,7 +106,7 @@ class WebPlayer
$transcode_settings = $media->get_transcode_settings(null, 'webplayer');
if ($transcode_settings) {
$types['real'] = $transcode_settings['format'];
- $transcode = true;
+ $transcode = true;
}
}
}
@@ -114,24 +118,47 @@ class WebPlayer
}
if ($urlinfo['type'] == 'song') {
- if ($types['real'] == "ogg") $types['player'] = "oga";
- else if ($types['real'] == "mp4") $types['player'] = "m4a";
- } else if ($urlinfo['type'] == 'video') {
- if ($types['real'] == "ogg") $types['player'] = "ogv";
- else if ($types['real'] == "webm") $types['player'] = "webmv";
- else if ($types['real'] == "mp4") $types['player'] = "m4v";
+ if ($types['real'] == "ogg" || $types['real'] == "opus") {
+ $types['player'] = "oga";
+ } else {
+ if ($types['real'] == "mp4") {
+ $types['player'] = "m4a";
+ }
+ }
+ } else {
+ if ($urlinfo['type'] == 'video') {
+ if ($types['real'] == "ogg") {
+ $types['player'] = "ogv";
+ } else {
+ if ($types['real'] == "webm") {
+ $types['player'] = "webmv";
+ } else {
+ if ($types['real'] == "mp4") {
+ $types['player'] = "m4v";
+ }
+ }
+ }
+ }
}
- } else if ($item->type == 'live_stream') {
- $types['real'] = $item->codec;
- if ($types['real'] == "ogg") $types['player'] = "oga";
} else {
- $ext = pathinfo($item->url, PATHINFO_EXTENSION);
- if (!empty($ext)) $types['real'] = $ext;
+ if ($item->type == 'live_stream') {
+ $types['real'] = $item->codec;
+ if ($types['real'] == "ogg" || $types['real'] == "opus") {
+ $types['player'] = "oga";
+ }
+ } else {
+ $ext = pathinfo($item->url, PATHINFO_EXTENSION);
+ if (!empty($ext)) {
+ $types['real'] = $ext;
+ }
+ }
}
- if (empty($types['player'])) $types['player'] = $types['real'];
+ if (empty($types['player'])) {
+ $types['player'] = $types['real'];
+ }
- debug_event("webplayer.class.php", "Types {".json_encode($types)."}", 5);
+ debug_event("webplayer.class.php", "Types {" . json_encode($types) . "}", 5);
return $types;
}
@@ -209,10 +236,11 @@ class WebPlayer
{
$js = array();
foreach (array('title', 'author') as $member) {
- if ($member == "author")
+ if ($member == "author") {
$kmember = "artist";
- else
+ } else {
$kmember = $member;
+ }
$js[$kmember] = $item->$member;
}
@@ -220,20 +248,24 @@ class WebPlayer
$types = self::get_types($item, $force_type);
- $media = null;
+ $media = null;
$urlinfo = Stream_URL::parse($url);
- $url = $urlinfo['base_url'];
+ $url = $urlinfo['base_url'];
if ($urlinfo['id'] && Core::is_media($urlinfo['type'])) {
$media = new $urlinfo['type']($urlinfo['id']);
- } else if ($urlinfo['id'] && $urlinfo['type'] == 'song_preview') {
- $media = new Song_Preview($urlinfo['id']);
- } else if (isset($urlinfo['demo_id'])) {
- $democratic = new Democratic($urlinfo['demo_id']);
- if ($democratic->id) {
- $song_id = $democratic->get_next_object();
- if ($song_id) {
- $media = new Song($song_id);
+ } else {
+ if ($urlinfo['id'] && $urlinfo['type'] == 'song_preview') {
+ $media = new Song_Preview($urlinfo['id']);
+ } else {
+ if (isset($urlinfo['demo_id'])) {
+ $democratic = new Democratic($urlinfo['demo_id']);
+ if ($democratic->id) {
+ $song_id = $democratic->get_next_object();
+ if ($song_id) {
+ $media = new Song($song_id);
+ }
+ }
}
}
}
@@ -241,14 +273,15 @@ class WebPlayer
if ($media != null) {
$media->format();
if ($urlinfo['type'] == 'song') {
- $js['artist_id'] = $media->artist;
- $js['album_id'] = $media->album;
+ $js['artist_id'] = $media->artist;
+ $js['album_id'] = $media->album;
$js['replaygain_track_gain'] = $media->replaygain_track_gain;
$js['replaygain_track_peak'] = $media->replaygain_track_peak;
$js['replaygain_album_gain'] = $media->replaygain_album_gain;
$js['replaygain_album_peak'] = $media->replaygain_album_peak;
}
- $js['media_id'] = $media->id;
+ $js['media_id'] = $media->id;
+ $js['media_type'] = $urlinfo['type'];
if ($media->type != $types['real']) {
$url .= '&transcode_to=' . $types['real'];
@@ -257,12 +290,12 @@ class WebPlayer
}
$js['filetype'] = $types['player'];
- $js['url'] = $url;
- if ($urlinfo['type'] == 'song') {
+ $js['url'] = $url;
+ if ($urlinfo['type'] == 'song' || $urlinfo['type'] == 'podcast_episode') {
$js['poster'] = $item->image_url;
}
- debug_event("webplayer.class.php", "Return get_media_js_param {".json_encode($js)."}", 5);
+ debug_event("webplayer.class.php", "Return get_media_js_param {" . json_encode($js) . "}", 5);
return json_encode($js);
}
diff --git a/sources/lib/class/xml_data.class.php b/sources/lib/class/xml_data.class.php
index 0d7869e..0ff1840 100644
--- a/sources/lib/class/xml_data.class.php
+++ b/sources/lib/class/xml_data.class.php
@@ -2,22 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; version 2
- * of the License.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -31,9 +30,9 @@
class XML_Data
{
// 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 $type = '';
+ private static $type = '';
/**
* constructor
@@ -55,7 +54,7 @@ class XML_Data
*/
public static function set_offset($offset)
{
- $offset = intval($offset);
+ $offset = intval($offset);
self::$offset = $offset;
} // set_offset
@@ -73,7 +72,7 @@ class XML_Data
return false;
}
- $limit = intval($limit);
+ $limit = intval($limit);
self::$limit = $limit;
} // set_limit
@@ -140,9 +139,9 @@ class XML_Data
* @see _header()
* @return string return xml
*/
- public static function header()
+ public static function header($title = null)
{
- return self::_header();
+ return self::_header($title);
} // header
/**
@@ -227,9 +226,9 @@ class XML_Data
foreach ($array as $key=>$value) {
$attribute = '';
// See if the key has attributes
- if (is_array($value) AND isset($value[''])) {
+ if (is_array($value) and isset($value[''])) {
$attribute = ' ' . $value[''];
- $key = $value['value'];
+ $key = $value['value'];
}
// If it's an array, run again
@@ -258,14 +257,14 @@ class XML_Data
*/
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);
}
$string = '';
foreach ($tags as $tag_id) {
- $tag = new Tag($tag_id);
+ $tag = new Tag($tag_id);
$counts = $tag->count();
$string .= "\n" .
"\tname]]>\n" .
@@ -294,7 +293,7 @@ class XML_Data
*/
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);
}
@@ -306,7 +305,7 @@ class XML_Data
$artist = new Artist($artist_id);
$artist->format();
- $rating = new Rating($artist_id,'artist');
+ $rating = new Rating($artist_id,'artist');
$tag_string = self::tags_string($artist->tags);
$string .= "id . "\">\n" .
@@ -339,7 +338,7 @@ class XML_Data
*/
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);
}
@@ -392,7 +391,7 @@ class XML_Data
*/
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);
}
@@ -402,7 +401,7 @@ class XML_Data
foreach ($playlists as $playlist_id) {
$playlist = new Playlist($playlist_id);
$playlist->format();
- $item_total = $playlist->get_song_count();
+ $item_total = $playlist->get_media_count('song');
// Build this element
$string .= "id\">\n" .
@@ -427,7 +426,7 @@ class XML_Data
*/
public static function songs($songs,$playlist_data='')
{
- 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);
}
@@ -439,14 +438,16 @@ class XML_Data
foreach ($songs as $song_id) {
$song = new Song($song_id);
- // If the song id is invalid/null
- if (!$song->id) {
+ // If the song id is invalid/null or disabled
+ if (!$song->id || !$song->enabled) {
continue;
}
+
+ $song->format();
$playlist_track_string = self::playlist_song_tracks_string($song, $playlist_data);
- $tag_string = self::tags_string(Tag::get_top_tags('song', $song_id));
- $rating = new Rating($song_id, 'song');
- $art_url = Art::url($song->album, 'album', $_REQUEST['auth']);
+ $tag_string = self::tags_string(Tag::get_top_tags('song', $song_id));
+ $rating = new Rating($song_id, 'song');
+ $art_url = Art::url($song->album, 'album', $_REQUEST['auth']);
$string .= "id . "\">\n" .
"\ttitle . "]]>\n" .
@@ -454,27 +455,47 @@ class XML_Data
'">get_artist_name() .
"]]>\n" .
"\talbum .
- '">get_album_name().
- "]]>\n" .
- $tag_string .
+ '">get_album_name() .
+ "]]>\n";
+ if ($song->albumartist) {
+ $string .= "\talbumartist .
+ "\">get_album_artist_name() . "]]>\n";
+ }
+ $string .= $tag_string .
"\tfile . "]]>\n" .
"\t\n" .
$playlist_track_string .
"\t\n" .
"\t" . $song->year . "\n" .
- "\t" . $song->bitrate . "\n".
- "\t" . $song->mode . "\n".
+ "\t" . $song->bitrate . "\n" .
+ "\t" . $song->rate . "\n" .
+ "\t" . $song->mode . "\n" .
"\t" . $song->mime . "\n" .
"\tid, '', 'api') . "]]>\n" .
- "\t" . $song->size . "\n".
- "\t" . $song->mbid . "\n".
- "\t" . $song->album_mbid . "\n".
- "\t" . $song->artist_mbid . "\n".
+ "\t" . $song->size . "\n" .
+ "\t" . $song->mbid . "\n" .
+ "\t" . $song->album_mbid . "\n" .
+ "\t" . $song->artist_mbid . "\n" .
+ "\t" . $song->albumartist_mbid . "\n" .
"\t\n" .
"\t" . ($rating->get_user_rating() ?: 0) . "\n" .
"\t" . ($rating->get_user_rating() ?: 0) . "\n" .
"\t" . ($rating->get_average_rating() ?: 0) . "\n" .
- "\n";
+ "\t" . $song->composer . "\n" .
+ "\t" . $song->channels . "\n" .
+ "\tcomment . "]]>\n";
+
+ $string .= "\tlabel . "]]>\n"
+ . "\t" . $song->language . "\n"
+ . "\t" . $song->replaygain_album_gain . "\n"
+ . "\t" . $song->replaygain_album_peak . "\n"
+ . "\t" . $song->replaygain_track_gain . "\n"
+ . "\t" . $song->replaygain_track_peak . "\n";
+ foreach ($song->tags as $tag) {
+ $string .= "\t\n";
+ }
+
+ $string .= "\n";
} // end foreach
return self::_header() . $string . self::_footer();
@@ -490,7 +511,7 @@ class XML_Data
*/
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);
}
@@ -538,8 +559,8 @@ class XML_Data
$song->format();
//FIXME: This is duplicate code and so wrong, functions need to be improved
- $tag = new Tag($song->tags['0']);
- $song->genre = $tag->id;
+ $tag = new Tag($song->tags['0']);
+ $song->genre = $tag->id;
$song->f_genre = $tag->name;
$tag_string = self::tags_string($song->tags);
@@ -642,7 +663,7 @@ class XML_Data
"\t\t" . $shout->date . "\n" .
"\t\ttext . "]]>\n";
if ($user->id) {
- $string .= "\t\tusername ."]]>";
+ $string .= "\t\tusername . "]]>";
}
$string .= "\tn";
}
@@ -653,6 +674,38 @@ class XML_Data
return $final;
} // shouts
+ /**
+ * timeline
+ *
+ * This handles creating an xml document for an activity list
+ *
+ * @param int[] $activities Activity identifier list
+ * @return string return xml
+ */
+ public static function timeline($activities)
+ {
+ $string = "\n";
+ foreach ($activities as $aid) {
+ $activity = new Useractivity($aid);
+ $shout->format();
+ $user = new User($activity->user);
+ $string .= "\t\n" .
+ "\t\t" . $activity->activity_date . "\n" .
+ "\t\tobject_type . "]]>\n" .
+ "\t\t" . $activity->object_id . "\n" .
+ "\t\ttext . "]]>\n";
+ if ($user->id) {
+ $string .= "\t\tusername . "]]>";
+ }
+ $string .= "\tn";
+ }
+ $string .= "\n";
+
+ $final = self::_header() . $string . self::_footer();
+
+ return $final;
+ } // timeline
+
/**
* rss_feed
*
@@ -692,16 +745,16 @@ class XML_Data
*
* @return string Header xml tag.
*/
- private static function _header()
+ private static function _header($title = null)
{
switch (self::$type) {
case 'xspf':
$header = "\n" .
- "\n " .
- "Ampache XSPF Playlist\n" .
+ "\n" .
+ "" . ($title ?: "Ampache XSPF Playlist") . "\n" .
"" . scrub_out(AmpConfig::get('site_title')) . "\n" .
"" . scrub_out(AmpConfig::get('site_title')) . "\n" .
- "". AmpConfig::get('web_path') ."\n" .
+ "" . AmpConfig::get('web_path') . "\n" .
"\n";
break;
case 'itunes':
@@ -762,29 +815,30 @@ class XML_Data
public static function podcast(library_item $libitem)
{
- $xml = new SimpleXMLElement('');
- $xml->addAttribute("version", "2.0");
+ $xml = new SimpleXMLElement('');
$xml->addAttribute("xmlns:xmlns:atom", "http://www.w3.org/2005/Atom");
$xml->addAttribute("xmlns:xmlns:itunes", "http://www.itunes.com/dtds/podcast-1.0.dtd");
+ $xml->addAttribute("version", "2.0");
$xchannel = $xml->addChild("channel");
$xchannel->addChild("title", $libitem->get_fullname() . " Podcast");
- $xlink = $xchannel->addChild("atom:link");
- $xlink->addAttribute("type", "text/html");
- $xlink->addAttribute("href", $libitem->link);
+ $xlink = $xchannel->addChild("atom:link", htmlentities($libitem->link));
if (Art::has_db($libitem->id, get_class($libitem))) {
$ximg = $xchannel->addChild("xmlns:itunes:image");
$ximg->addAttribute("href", Art::url($libitem->id, get_class($libitem)));
}
$summary = $libitem->get_description();
if (!empty($summary)) {
+ $summary = htmlentities($summary);
+ $xchannel->addChild("description", $summary);
$xchannel->addChild("xmlns:itunes:summary", $summary);
}
+ $xchannel->addChild("generator", "Ampache");
$xchannel->addChild("xmlns:itunes:category", "Music");
$owner = $libitem->get_user_owner();
if ($owner) {
$user_owner = new User($owner);
$user_owner->format();
- $xowner = $xitem->addChild("xmlns:itunes:owner");
+ $xowner = $xchannel->addChild("xmlns:itunes:owner");
$xowner->addChild("xmlns:itunes:name", $user_owner->f_name);
}
@@ -793,33 +847,38 @@ class XML_Data
$media = new $media_info['object_type']($media_info['object_id']);
$media->format();
$xitem = $xchannel->addChild("item");
- $xitem->addChild("title", $media->get_fullname());
+ $xitem->addChild("title", htmlentities($media->get_fullname()));
if ($media->f_artist) {
$xitem->addChild("xmlns:itunes:author", $media->f_artist);
}
- $xmlink = $xitem->addChild("link");
- $xmlink->addAttribute("href", $media->link);
- $xitem->addChild("guid", $media->link);
+ $xmlink = $xitem->addChild("link", htmlentities($media->link));
+ $xitem->addChild("guid", htmlentities($media->link));
if ($media->addition_time) {
$xitem->addChild("pubDate", date("r", $media->addition_time));
}
$description = $media->get_description();
if (!empty($description)) {
- $xitem->addChild("description", $description);
+ $xitem->addChild("description", htmlentities($description));
}
$xitem->addChild("xmlns:itunes:duration", $media->f_time);
- $xencl = $xitem->addChild("enclosure");
- $xencl->addAttribute("type", $media->mime);
- $xencl->addAttribute("length", $media->size);
- $surl = $media_info['object_type']::play_url($media_info['object_id']);
- $xencl->addAttribute("url", $surl);
+ if ($media->mime) {
+ $surl = $media_info['object_type']::play_url($media_info['object_id']);
+ $xencl = $xitem->addChild("enclosure");
+ $xencl->addAttribute("type", $media->mime);
+ $xencl->addAttribute("length", $media->size);
+ $xencl->addAttribute("url", $surl);
+ }
}
$xmlstr = $xml->asXml();
// Format xml output
$dom = new DOMDocument();
- $dom->loadXML($xmlstr);
- $dom->formatOutput = true;
- return $dom->saveXML($dom->documentElement);
+ if ($dom->loadXML($xmlstr) !== false) {
+ $dom->formatOutput = true;
+ return $dom->saveXML();
+ } else {
+ return $xmlstr;
+ }
}
} // XML_Data
+
diff --git a/sources/lib/debug.lib.php b/sources/lib/debug.lib.php
index 740fa59..dcc472c 100644
--- a/sources/lib/debug.lib.php
+++ b/sources/lib/debug.lib.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -81,6 +81,14 @@ function check_php_pdo_mysql()
return class_exists('PDO') ? in_array('mysql', PDO::getAvailableDrivers()) : false;
}
+function check_mbstring_func_overload()
+{
+ if ( ini_get('mbstring.func_overload') > 0) {
+ return false;
+ }
+ return true;
+}
+
/**
* check_config_values
* checks to make sure that they have at least set the needed variables
@@ -114,12 +122,11 @@ function check_config_values($conf)
}
if (isset($conf['debug'])) {
if (!isset($conf['log_path'])) {
- return false;
+ return false;
}
}
return true;
-
} // check_config_values
/**
@@ -138,7 +145,6 @@ function check_php_memory()
}
return true;
-
} // check_php_memory
/**
@@ -150,7 +156,6 @@ function check_php_timelimit()
{
$current = intval(ini_get('max_execution_time'));
return ($current >= 60 || $current == 0);
-
} // check_php_timelimit
/**
@@ -174,7 +179,7 @@ function check_override_memory()
/* Check memory */
$current_memory = ini_get('memory_limit');
$current_memory = substr($current_memory,0,strlen($current_memory)-1);
- $new_limit = ($current_memory+16) . "M";
+ $new_limit = ($current_memory+16) . "M";
/* Bump it by 16 megs (for getid3)*/
if (!ini_set('memory_limit',$new_limit)) {
@@ -214,8 +219,8 @@ function check_override_exec_time()
function check_upload_size()
{
$upload_max = return_bytes(ini_get('upload_max_filesize'));
- $post_max = return_bytes(ini_get('post_max_size'));
- $mini = 20971520; // 20M
+ $post_max = return_bytes(ini_get('post_max_size'));
+ $mini = 20971520; // 20M
return (($upload_max >= $mini || $upload_max <= 0) && ($post_max >= $mini || $post_max <= 0));
}
@@ -235,9 +240,14 @@ function check_php_simplexml()
return function_exists('simplexml_load_string');
}
+function check_php_gd()
+{
+ return (extension_loaded('gd') || extension_loaded('gd2'));
+}
+
function return_bytes($val)
{
- $val = trim($val);
+ $val = trim($val);
$last = strtolower($val[strlen($val)-1]);
switch ($last) {
// The 'G' modifier is available since PHP 5.1.0
@@ -253,6 +263,11 @@ function return_bytes($val)
return $val;
}
+function check_dependencies_folder()
+{
+ return file_exists(AmpConfig::get('prefix') . '/lib/vendor');
+}
+
/**
* check_config_writable
* This checks whether we can write the config file
diff --git a/sources/lib/general.lib.php b/sources/lib/general.lib.php
index 138186b..dc9ddf0 100644
--- a/sources/lib/general.lib.php
+++ b/sources/lib/general.lib.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -33,12 +33,11 @@ function set_memory_limit($new_limit)
}
$current_limit = UI::unformat_bytes($current_limit);
- $new_limit = UI::unformat_bytes($new_limit);
+ $new_limit = UI::unformat_bytes($new_limit);
if ($current_limit < $new_limit) {
ini_set (memory_limit, $new_limit);
}
-
} // set_memory_limit
/**
@@ -47,16 +46,16 @@ function set_memory_limit($new_limit)
*/
function generate_password($length)
{
- $vowels = 'aAeEuUyY12345';
+ $vowels = 'aAeEuUyY12345';
$consonants = 'bBdDgGhHjJmMnNpPqQrRsStTvVwWxXzZ6789';
- $password = '';
+ $password = '';
$alt = time() % 2;
for ($i = 0; $i < $length; $i++) {
if ($alt == 1) {
$password .= $consonants[(rand(0,strlen($consonants)-1))];
- $alt = 0;
+ $alt = 0;
} else {
$password .= $vowels[(rand(0,strlen($vowels)-1))];
$alt = 1;
@@ -64,7 +63,6 @@ function generate_password($length)
}
return $password;
-
} // generate_password
/**
@@ -93,7 +91,6 @@ function scrub_in($input)
function scrub_out($string)
{
return htmlentities($string, ENT_QUOTES, AmpConfig::get('site_charset'));
-
} // scrub_out
/**
@@ -103,7 +100,6 @@ function scrub_out($string)
function unhtmlentities($string)
{
return html_entity_decode($string, ENT_QUOTES, AmpConfig::get('site_charset'));
-
} //unhtmlentities
/**
@@ -132,7 +128,6 @@ function make_bool($string)
}
return (bool) $string;
-
} // make_bool
/**
@@ -142,7 +137,6 @@ function make_bool($string)
function invert_bool($value)
{
return make_bool($value) ? false : true;
-
} // invert_bool
/**
@@ -164,12 +158,10 @@ function get_languages()
$results = array();
while (false !== ($file = readdir($handle))) {
-
$full_file = AmpConfig::get('prefix') . '/locale/' . $file;
/* 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) {
case 'af_ZA'; $name = 'Afrikaans'; break; /* Afrikaans */
case 'bg_BG'; $name = 'Български'; break; /* Bulgarian */
@@ -216,13 +208,12 @@ function get_languages()
case 'ar_SA'; $name = 'العربية'; break; /* Arabic */
case 'he_IL'; $name = 'עברית'; break; /* Hebrew */
case 'fa_IR'; $name = 'فارسي'; break; /* Farsi */
- default: $name = T_('Unknown'); break;
+ default: $name = T_('Unknown'); break;
} // end switch
$results[$file] = $name;
}
-
} // end while
// Sort the list of languages by country code
@@ -232,7 +223,6 @@ function get_languages()
$results = array( "en_US" => "English (US)" ) + $results;
return $results;
-
} // get_languages
/**
@@ -266,7 +256,6 @@ function translate_pattern_code($code)
}
return false;
-
} // translate_pattern_code
/**
@@ -279,8 +268,8 @@ function generate_config($current)
{
// Start building the new config file
$distfile = AmpConfig::get('prefix') . '/config/ampache.cfg.php.dist';
- $handle = fopen($distfile,'r');
- $dist = fread($handle,filesize($distfile));
+ $handle = fopen($distfile,'r');
+ $dist = fread($handle,filesize($distfile));
fclose($handle);
$data = explode("\n",$dist);
@@ -290,7 +279,6 @@ function generate_config($current)
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+[\'\"]{0}(.*)[\'\"]{0}$/",$line,$matches)) {
-
$key = $matches[1];
$value = $matches[2];
@@ -342,13 +330,17 @@ if (!function_exists('apache_request_headers')) {
$headers = array();
foreach ($_SERVER as $name => $value) {
if (substr($name, 0, 5) == 'HTTP_') {
- $name = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))));
+ $name = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))));
$headers[$name] = $value;
- } else if ($name == "CONTENT_TYPE") {
- $headers["Content-Type"] = $value;
- } else if ($name == "CONTENT_LENGTH") {
- $headers["Content-Length"] = $value;
- }
+ } else {
+ if ($name == "CONTENT_TYPE") {
+ $headers["Content-Type"] = $value;
+ } else {
+ if ($name == "CONTENT_LENGTH") {
+ $headers["Content-Length"] = $value;
+ }
+ }
+ }
}
return $headers;
}
diff --git a/sources/lib/i18n.php b/sources/lib/i18n.php
index fc3608f..51bd454 100644
--- a/sources/lib/i18n.php
+++ b/sources/lib/i18n.php
@@ -2,24 +2,26 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
+use Gettext\Translator;
+
/**
* load_gettext
* Sets up our local gettext settings.
@@ -28,18 +30,26 @@
*/
function load_gettext()
{
- $lang = AmpConfig::get('lang');
- $charset = AmpConfig::get('site_charset') ?: 'UTF-8';
- $locale = $lang . '.' . $charset;
- //debug_event('i18n', 'Setting locale to ' . $locale, 5);
- T_setlocale(LC_MESSAGES, $locale);
- /* Bind the Text Domain */
- T_bindtextdomain('messages', AmpConfig::get('prefix') . "/locale/");
- T_bind_textdomain_codeset('messages', $charset);
- T_textdomain('messages');
- //debug_event('i18n', 'gettext is ' . (locale_emulation() ? 'emulated' : 'native'), 5);
+ $lang = AmpConfig::get('lang');
+ $popath = AmpConfig::get('prefix') . '/locale/' . $lang . '/LC_MESSAGES/messages.po';
+
+ $t = new Translator();
+ if (file_exists($popath)) {
+ $translations = Gettext\Translations::fromPoFile($popath);
+ $t->loadTranslations($translations);
+ }
+ $t->register();
} // load_gettext
+function T_($msgid)
+{
+ if (function_exists('__')) {
+ return __($msgid);
+ }
+
+ return $msgid;
+}
+
/**
* gettext_noop
*
diff --git a/sources/lib/init-tiny.php b/sources/lib/init-tiny.php
index cac7464..8a544f3 100644
--- a/sources/lib/init-tiny.php
+++ b/sources/lib/init-tiny.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -33,8 +33,8 @@ error_reporting(E_ERROR); // Only show fatal errors in production
$load_time_begin = microtime(true);
$ampache_path = dirname(__FILE__);
-$prefix = realpath($ampache_path . "/../");
-$configfile = $prefix . '/config/ampache.cfg.php';
+$prefix = realpath($ampache_path . "/../");
+$configfile = $prefix . '/config/ampache.cfg.php';
// We still allow scripts to run (it could be the purpose of the maintenance)
if (!defined('CLI')) {
@@ -46,16 +46,18 @@ if (!defined('CLI')) {
require_once $prefix . '/lib/general.lib.php';
require_once $prefix . '/lib/class/ampconfig.class.php';
require_once $prefix . '/lib/class/core.class.php';
-require_once $prefix . '/modules/php-gettext/gettext.inc';
// Define some base level config options
AmpConfig::set('prefix', $prefix);
-// Register the autoloader
+// Register autoloaders
spl_autoload_register(array('Core', 'autoload'), true, true);
-
-require_once $prefix . '/modules/requests/Requests.php';
-Requests::register_autoloader();
+$composer_autoload = $prefix . '/lib/vendor/autoload.php';
+if (file_exists($composer_autoload)) {
+ require_once $composer_autoload;
+ require_once $prefix . '/lib/vendor/Afterster/php-echonest-api/lib/EchoNest/Autoloader.php';
+ EchoNest_Autoloader::register();
+}
// Check to see if this is http or https
if ((isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' )
@@ -67,8 +69,10 @@ if ((isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PRO
if (isset($_SERVER['HTTP_X_FORWARDED_PORT'])) {
$http_port = $_SERVER['HTTP_X_FORWARDED_PORT'];
-} else if (isset($_SERVER['SERVER_PORT'])) {
- $http_port = $_SERVER['SERVER_PORT'];
+} else {
+ if (isset($_SERVER['SERVER_PORT'])) {
+ $http_port = $_SERVER['SERVER_PORT'];
+ }
}
if (!isset($http_port) || empty($http_port)) {
$http_port = 80;
diff --git a/sources/lib/init.php b/sources/lib/init.php
index c48e50d..69d18fd 100644
--- a/sources/lib/init.php
+++ b/sources/lib/init.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -25,7 +25,7 @@
ob_start();
$ampache_path = dirname(__FILE__);
-$prefix = realpath($ampache_path . "/../");
+$prefix = realpath($ampache_path . "/../");
require_once $prefix . '/lib/init-tiny.php';
// Explicitly load and enable the custom session handler.
@@ -35,7 +35,9 @@ Session::_auto_init();
// Set up for redirection on important error cases
$path = get_web_path();
-$path = $http_type . $_SERVER['HTTP_HOST'] . $path;
+if (isset($_SERVER['HTTP_HOST'])) {
+ $path = $http_type . $_SERVER['HTTP_HOST'] . $path;
+}
// Check to make sure the config file exists. If it doesn't then go ahead and
// send them over to the install script.
@@ -53,7 +55,7 @@ if (!file_exists($configfile)) {
// Verify that a few important but commonly disabled PHP functions exist and
// that we're on a usable version
-if (!check_php()) {
+if (!check_php() || !check_dependencies_folder()) {
$link = $path . '/test.php';
}
@@ -65,14 +67,14 @@ if (!empty($link)) {
$results['load_time_begin'] = $load_time_begin;
/** This is the version.... fluf nothing more... **/
-$results['version'] = '3.8.0';
-$results['int_config_version'] = '29';
+$results['version'] = '3.8.2';
+$results['int_config_version'] = '33';
if (!empty($results['force_ssl'])) {
$http_type = 'https://';
}
-if ($ow_config) {
+if (isset($ow_config) && is_array($ow_config)) {
foreach ($ow_config as $key => $value) {
$results[$key] = $value;
}
@@ -80,16 +82,20 @@ if ($ow_config) {
$results['raw_web_path'] = $results['web_path'];
if (empty($results['http_host'])) {
- $results['http_host'] = $_SERVER['HTTP_HOST'];
+ $results['http_host'] = $_SERVER['SERVER_NAME'];
}
if (empty($results['local_web_path'])) {
$results['local_web_path'] = $http_type . $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'] . $results['raw_web_path'];
}
-$results['web_path'] = $http_type . $results['http_host'] . $results['web_path'];
$results['http_port'] = (!empty($results['http_port'])) ? $results['http_port'] : $http_port;
+$results['web_path'] = $http_type . $results['http_host'] .
+ (($results['http_port'] != 80 && $results['http_port'] != 443) ? ':' . $results['http_port'] : '') .
+ $results['web_path'];
$results['site_charset'] = $results['site_charset'] ?: 'UTF-8';
$results['raw_web_path'] = $results['raw_web_path'] ?: '/';
-$results['max_upload_size'] = $results['max_upload_size'] ?: 1048576;
+if (!isset($results['max_upload_size'])) {
+ $results['max_upload_size'] = 1048576;
+}
$_SERVER['SERVER_NAME'] = $_SERVER['SERVER_NAME'] ?: '';
if (isset($results['user_ip_cardinality']) && !$results['user_ip_cardinality']) {
@@ -97,30 +103,16 @@ if (isset($results['user_ip_cardinality']) && !$results['user_ip_cardinality'])
}
/* Variables needed for Auth class */
-$results['cookie_path'] = $results['raw_web_path'];
-$results['cookie_domain'] = $results['http_port'];
+$results['cookie_path'] = $results['raw_web_path'];
+$results['cookie_domain'] = $results['http_port'];
$results['cookie_life'] = $results['session_cookielife'];
-$results['cookie_secure'] = $results['session_cookiesecure'];
+$results['cookie_secure'] = $results['session_cookiesecure'];
// Library and module includes we can't do with the autoloader
-require_once $prefix . '/modules/getid3/getid3.php';
-require_once $prefix . '/modules/phpmailer/class.phpmailer.php';
-require_once $prefix . '/modules/phpmailer/class.smtp.php';
require_once $prefix . '/modules/infotools/AmazonSearchEngine.class.php';
-require_once $prefix . '/modules/musicbrainz/MusicBrainz.php';
-require_once $prefix . '/modules/musicbrainz/Exception.php';
-require_once $prefix . '/modules/musicbrainz/Clients/MbClient.php';
-require_once $prefix . '/modules/musicbrainz/Clients/RequestsMbClient.php';
-require_once $prefix . '/modules/musicbrainz/Artist.php';
-require_once $prefix . '/modules/musicbrainz/Filters/AbstractFilter.php';
-require_once $prefix . '/modules/musicbrainz/Filters/FilterInterface.php';
-require_once $prefix . '/modules/musicbrainz/Filters/ArtistFilter.php';
-require_once $prefix . '/modules/ampacheapi/AmpacheApi.lib.php';
-require_once $prefix . '/modules/EchoNest/Autoloader.php';
-EchoNest_Autoloader::register();
-
-require_once $prefix . '/modules/SabreDAV/autoload.php';
+//require_once $prefix . '/lib/vendor/phpmailer/phpmailer/class.phpmailer.php';
+//require_once $prefix . '/lib/vendor/phpmailer/phpmailer/class.smtp.php';
/* Temp Fixes */
$results = Preference::fix_preferences($results);
@@ -180,33 +172,34 @@ if (!defined('NO_SESSION') && AmpConfig::get('use_auth')) {
/* Load preferences and theme */
$GLOBALS['user']->update_last_seen();
} elseif (!AmpConfig::get('use_auth')) {
- $auth['success'] = 1;
- $auth['username'] = '-1';
- $auth['fullname'] = "Ampache User";
- $auth['id'] = -1;
+ $auth['success'] = 1;
+ $auth['username'] = '-1';
+ $auth['fullname'] = "Ampache User";
+ $auth['id'] = -1;
$auth['offset_limit'] = 50;
- $auth['access'] = AmpConfig::get('default_auth_level') ? User::access_name_to_level(AmpConfig::get('default_auth_level')) : '100';
+ $auth['access'] = AmpConfig::get('default_auth_level') ? User::access_name_to_level(AmpConfig::get('default_auth_level')) : '100';
if (!Session::exists('interface', $_COOKIE[AmpConfig::get('session_name')])) {
Session::create_cookie();
Session::create($auth);
Session::check();
- $GLOBALS['user'] = new User($auth['username']);
+ $GLOBALS['user'] = new User($auth['username']);
$GLOBALS['user']->username = $auth['username'];
$GLOBALS['user']->fullname = $auth['fullname'];
- $GLOBALS['user']->access = intval($auth['access']);
+ $GLOBALS['user']->access = intval($auth['access']);
} else {
Session::check();
if ($_SESSION['userdata']['username']) {
$GLOBALS['user'] = User::get_from_username($_SESSION['userdata']['username']);
} else {
- $GLOBALS['user'] = new User($auth['username']);
- $GLOBALS['user']->id = -1;
+ $GLOBALS['user'] = new User($auth['username']);
+ $GLOBALS['user']->id = -1;
$GLOBALS['user']->username = $auth['username'];
$GLOBALS['user']->fullname = $auth['fullname'];
- $GLOBALS['user']->access = intval($auth['access']);
+ $GLOBALS['user']->access = intval($auth['access']);
}
- if (!$GLOBALS['user']->id AND !AmpConfig::get('demo_mode')) {
- Auth::logout(session_id()); exit;
+ if (!$GLOBALS['user']->id and !AmpConfig::get('demo_mode')) {
+ Auth::logout(session_id());
+ exit;
}
$GLOBALS['user']->update_last_seen();
}
@@ -221,14 +214,16 @@ else {
} else {
$GLOBALS['user'] = new User();
}
-
} // If NO_SESSION passed
-$GLOBALS['user']->format(false);
-
// Load the Preferences from the database
Preference::init();
+// Load gettext mojo
+load_gettext();
+
+$GLOBALS['user']->format(false);
+
if (session_id()) {
Session::extend(session_id());
// We only need to create the tmp playlist if we have a session
@@ -239,9 +234,6 @@ if (session_id()) {
AmpConfig::set('ajax_url', AmpConfig::get('web_path') . '/server/ajax.server.php', true);
AmpConfig::set('ajax_server', AmpConfig::get('web_path') . '/server', true);
-// Load gettext mojo
-load_gettext();
-
/* Set CHARSET */
header ("Content-Type: text/html; charset=" . AmpConfig::get('site_charset'));
diff --git a/sources/lib/install.lib.php b/sources/lib/install.lib.php
index 98abfc9..5c1f015 100644
--- a/sources/lib/install.lib.php
+++ b/sources/lib/install.lib.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -26,31 +26,31 @@
*/
function split_sql($sql)
{
- $sql = trim($sql);
- $sql = preg_replace("/\n#[^\n]*\n/", "\n", $sql);
- $buffer = array();
- $ret = array();
- $in_string = false;
- for ($i=0; $i 0, we can ignore lazy comparison problems
if (!file_put_contents($config_file, $final)) {
- Error::add('general', T_('Error writing config file'));
+ AmpError::add('general', T_('Error writing config file'));
return false;
}
}
@@ -306,23 +305,23 @@ function install_create_config($download = false)
*/
function install_create_account($username, $password, $password2)
{
- if (!strlen($username) OR !strlen($password)) {
- Error::add('general', T_('No Username/Password specified'));
+ if (!strlen($username) or !strlen($password)) {
+ AmpError::add('general', T_('No Username/Password specified'));
return false;
}
if ($password !== $password2) {
- Error::add('general', T_('Passwords do not match'));
+ AmpError::add('general', T_('Passwords do not match'));
return false;
}
if (!Dba::check_database()) {
- Error::add('general', sprintf(T_('Database connection failed: %s'), Dba::error()));
+ AmpError::add('general', sprintf(T_('Database connection failed: %s'), Dba::error()));
return false;
}
if (!Dba::check_database_inserted()) {
- Error::add('general', sprintf(T_('Database select failed: %s'), Dba::error()));
+ AmpError::add('general', sprintf(T_('Database select failed: %s'), Dba::error()));
return false;
}
@@ -332,7 +331,7 @@ function install_create_account($username, $password, $password2)
$insert_id = User::create($username,'Administrator','','',$password,'100');
if (!$insert_id) {
- Error::add('general', sprintf(T_('Administrative user creation failed: %s'), Dba::error()));
+ AmpError::add('general', sprintf(T_('Administrative user creation failed: %s'), Dba::error()));
return false;
}
@@ -340,7 +339,6 @@ function install_create_account($username, $password, $password2)
User::fix_preferences('-1');
return true;
-
} // install_create_account
function command_exists($command)
@@ -350,7 +348,7 @@ function command_exists($command)
}
$whereIsCommand = (PHP_OS == 'WINNT') ? 'where' : 'which';
- $process = proc_open(
+ $process = proc_open(
"$whereIsCommand $command",
array(
0 => array("pipe", "r"), //STDIN
@@ -406,9 +404,9 @@ function install_config_transcode_mode($mode)
'transcode_mkv' => 'allowed',
);
if ($mode == 'ffmpeg' || $mode == 'avconv') {
- $trconfig['transcode_cmd'] = $mode;
- $trconfig['transcode_input'] = '-i %FILE%';
- $trconfig['waveform'] = 'true';
+ $trconfig['transcode_cmd'] = $mode;
+ $trconfig['transcode_input'] = '-i %FILE%';
+ $trconfig['waveform'] = 'true';
$trconfig['generate_video_preview'] = 'true';
AmpConfig::set_by_array($trconfig, true);
@@ -441,31 +439,33 @@ function install_config_use_case($case)
switch ($case) {
case 'minimalist':
- $trconfig['ratings'] = 'false';
- $trconfig['userflags'] = 'false';
- $trconfig['sociable'] = 'false';
- $trconfig['wanted'] = 'false';
- $trconfig['channel'] = 'false';
+ $trconfig['ratings'] = 'false';
+ $trconfig['userflags'] = 'false';
+ $trconfig['sociable'] = 'false';
+ $trconfig['wanted'] = 'false';
+ $trconfig['channel'] = 'false';
$trconfig['live_stream'] = 'false';
- $dbconfig['download'] = '0';
+ $dbconfig['download'] = '0';
$dbconfig['allow_video'] = '0';
- // Hide sidebar by default to have a better 'minimalist first look'.
+ // Default local UI preferences to have a better 'minimalist first look'.
setcookie('sidebar_state', 'collapsed', time() + (30 * 24 * 60 * 60), '/');
+ setcookie('browse_album_grid_view', 'false', time() + (30 * 24 * 60 * 60), '/');
+ setcookie('browse_artist_grid_view', 'false', time() + (30 * 24 * 60 * 60), '/');
break;
case 'community':
- $trconfig['use_auth'] = 'false';
- $trconfig['licensing'] = 'true';
- $trconfig['wanted'] = 'false';
- $trconfig['live_stream'] = 'false';
+ $trconfig['use_auth'] = 'false';
+ $trconfig['licensing'] = 'true';
+ $trconfig['wanted'] = 'false';
+ $trconfig['live_stream'] = 'false';
$trconfig['allow_public_registration'] = 'true';
- $trconfig['cookie_disclaimer'] = 'true';
- $trconfig['share'] = 'true';
+ $trconfig['cookie_disclaimer'] = 'true';
+ $trconfig['share'] = 'true';
- $dbconfig['download'] = '0';
- $dbconfig['share'] = '1';
- $dbconfig['home_now_playing'] = '0';
+ $dbconfig['download'] = '0';
+ $dbconfig['share'] = '1';
+ $dbconfig['home_now_playing'] = '0';
$dbconfig['home_recently_played'] = '0';
break;
default:
@@ -498,7 +498,7 @@ function install_config_backends(Array $backends)
$dbconfig['plex_backend'] = '1';
break;
case 'upnp':
- $dbconfig['upnp_backend'] = '1';
+ $dbconfig['upnp_backend'] = '1';
$dbconfig['stream_beautiful_url'] = '1';
break;
case 'daap':
diff --git a/sources/lib/javascript/.htaccess b/sources/lib/javascript/.htaccess
index 3b8fa6c..edb3570 100644
--- a/sources/lib/javascript/.htaccess
+++ b/sources/lib/javascript/.htaccess
@@ -1,9 +1,10 @@
# Apache 2.4
- Require all granted
+ Require all granted
# Apache 2.2
+ Order deny,allow
Allow from all
\ No newline at end of file
diff --git a/sources/lib/javascript/base.js b/sources/lib/javascript/base.js
index 49f5faa..8fe17d6 100644
--- a/sources/lib/javascript/base.js
+++ b/sources/lib/javascript/base.js
@@ -45,10 +45,10 @@ function initTabs()
$(function() {
var rightmenu = $("#rightbar");
- var rightsubmenu = $("#rightbar .submenu");
var pos = rightmenu.offset();
if (rightmenu.hasClass('rightbar-float')) {
$(window).scroll(function() {
+ var rightsubmenu = $("#rightbar .submenu");
if ($(this).scrollTop() > (pos.top)) {
rightmenu.addClass('fixedrightbar');
rightsubmenu.addClass('fixedrightbarsubmenu');
diff --git a/sources/lib/javascript/dynamicpage.js b/sources/lib/javascript/dynamicpage.js
index 6f502d3..a5047c5 100644
--- a/sources/lib/javascript/dynamicpage.js
+++ b/sources/lib/javascript/dynamicpage.js
@@ -88,7 +88,7 @@ $(function() {
$("body").delegate("form", "submit", function(e) {
// We do not support ajax post with files or login form, neither specific target
var $file = $(this).find("input[type=file]");
- if ($(this).attr('name') !== 'login' && (!$file || !$file.val() || $file.val() === "") && ($(this).attr('target') === undefined || $(this).attr('target') === '')) {
+ if ($(this).attr('name') !== 'login' && $(this).attr('name') !== 'export' && (!$file || !$file.val() || $file.val() === "") && ($(this).attr('target') === undefined || $(this).attr('target') === '')) {
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
diff --git a/sources/lib/javascript/search-data.php b/sources/lib/javascript/search-data.php
index 2ef41c0..059662d 100644
--- a/sources/lib/javascript/search-data.php
+++ b/sources/lib/javascript/search-data.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
diff --git a/sources/lib/javascript/search.js b/sources/lib/javascript/search.js
index 160fe97..c8c5bee 100644
--- a/sources/lib/javascript/search.js
+++ b/sources/lib/javascript/search.js
@@ -1,4 +1,4 @@
-// vim:set softtabstop=4 shiftwidth=4 expandtab:
+// vim:set softtabstop=4 shiftwidth=4 expandtab:
//
// Copyright 2010 - 2015 Ampache.org
// All rights reserved.
@@ -6,7 +6,7 @@
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License v2
// as published by the Free Software Foundation.
-//
+//
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -21,7 +21,7 @@ var rowIter = 1;
var rowCount = 0;
var SearchRow = {
- add: function(ruleType, operator, input) {
+ add: function (ruleType, operator, input, subtype) {
if (typeof(ruleType) != 'string') {
ruleType = 0;
}
@@ -54,8 +54,12 @@ var SearchRow = {
for (var i = 0 ; i < 5 ; i++) {
cells[i] = document.createElement('td');
}
-
+
cells[0].appendChild(SearchRow.constructOptions(ruleType, rowIter));
+ var select = SearchRow.createSubtypeOptions(ruleType, rowIter, subtype);
+ if (select) {
+ cells[0].appendChild(select);
+ }
cells[1].appendChild(SearchRow.constructOperators(ruleType, rowIter, operator));
cells[2].appendChild(SearchRow.constructInput(ruleType, rowIter, input));
cells[3].innerHTML = removeIcon;
@@ -67,10 +71,10 @@ var SearchRow = {
$('#searchtable').append(row);
rowCount++;
- $(cells[3]).on('click', function(){if(rowCount > 1) { this.parentNode.remove(); rowCount--; }});
+ $(cells[3]).on('click', function(){if(rowCount > 1) { $(this).parent().remove(); rowCount--; }});
rowIter++;
- },
+ },
constructInput: function(ruleType, ruleNumber, input) {
if (input === null || input === undefined) {
input = '';
@@ -86,7 +90,7 @@ var SearchRow = {
case 'input':
inputNode.setAttribute('type', widget['1']);
inputNode.setAttribute('value', input);
- break;
+ break;
case 'select':
jQuery.each(widget['1'], function(i) {
var option = document.createElement('option');
@@ -103,7 +107,14 @@ var SearchRow = {
option.innerHTML = widget['1'][i];
inputNode.appendChild(option);
});
- break;
+ break;
+ case 'subtypes':
+ inputNode = document.createElement(widget[1][0]);
+ inputNode.id = 'rule_' + ruleNumber + '_input';
+ inputNode.name = 'rule_' + ruleNumber + '_input';
+ inputNode.setAttribute('type', widget[1][1]);
+ inputNode.setAttribute('value', input);
+ break;
}
return inputNode;
@@ -159,8 +170,26 @@ var SearchRow = {
operator_cell.append(SearchRow.constructOperators(this.selectedIndex, targetID));
}
- var input = $('#rule_' + targetID + '_input');
+ var type = $(this).val();
+ jQuery.each(types, function (index, value) {
+ if (value.name == type) {
+ type = value
+ return false;
+ }
+ });
+
+ if (type['widget'][0] == 'subtypes') {
+ var $select = SearchRow.createSelect({
+ name: 'rule_' + targetID + '_subtype'
+ }, type['subtypes']);
+ $(this).after($select);
+ }
+ else {
+ $(this).closest('tr').find('select[name="subtype"]').remove();
+ }
+
+ var input = $('#rule_' + targetID + '_input');
if (input.type == 'text') {
var oldinput = input.value;
}
@@ -168,5 +197,28 @@ var SearchRow = {
var input_cell = input.parent();
input.remove();
input_cell.append(SearchRow.constructInput(this.selectedIndex, targetID, oldinput));
- }
+ },
+ createSelect: function (attributes, options, selected) {
+ var $select = $('\n";
break;
+ case 'disabled_custom_metadata_fields':
+ $ids = explode(',', $value);
+ $options = array();
+ $fieldRepository = new \Lib\Metadata\Repository\MetadataField();
+ foreach ($fieldRepository->findAll() as $field) {
+ $selected = in_array($field->getId(), $ids) ? ' selected="selected"' : '';
+ $options[] = '
' . $field->getName() . '
';
+ }
+ echo '';
+ break;
+ case 'lastfm_grant_link':
+ case 'librefm_grant_link':
+ // construct links for granting access Ampache application to Last.fm and Libre.fm
+ $plugin_name = ucfirst(str_replace('_grant_link', '', $name));
+ $plugin = new Plugin($plugin_name);
+ $url = $plugin->_plugin->url;
+ $api_key = rawurlencode(AmpConfig::get('lastfm_api_key'));
+ $callback = rawurlencode(AmpConfig::get('web_path') . '/preferences.php?tab=plugins&action=grant&plugin=' . $plugin_name);
+ echo "" . UI::get_icon('plugin', T_("Click for grant Ampache to ") . $plugin_name) . '';
+ break;
default:
if (preg_match('/_pass$/', $name)) {
echo '';
} else {
- echo '';
+ echo '';
}
break;
}
-
} // create_preference_input
+
diff --git a/sources/lib/rating.lib.php b/sources/lib/rating.lib.php
index 5bc7f45..c1b7849 100644
--- a/sources/lib/rating.lib.php
+++ b/sources/lib/rating.lib.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -28,8 +28,7 @@ function show_rating($object_id,$type)
{
$rating = new Rating($object_id,$type);
- require AmpConfig::get('prefix') . '/templates/show_object_rating.inc.php';
-
+ require AmpConfig::get('prefix') . UI::find_template('show_object_rating.inc.php');
} // show_rating
/**
@@ -55,5 +54,5 @@ function get_rating_name($score)
default:
return T_("Off the Charts!");
} // end switch
-
} // get_rating_name
+
diff --git a/sources/lib/themes.php b/sources/lib/themes.php
index 16cdbd4..ea4cfc3 100644
--- a/sources/lib/themes.php
+++ b/sources/lib/themes.php
@@ -2,21 +2,21 @@
/* vim:set softtabstop=4 shiftwidth=4 expandtab: */
/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -32,23 +32,16 @@ function get_themes()
$handle = opendir(AmpConfig::get('prefix') . '/themes');
if (!is_resource($handle)) {
- debug_event('theme', 'Failed to open /themes directory', 2);
- return array();
+ debug_event('theme', 'Failed to open /themes directory', 2);
+ return array();
}
$results = array();
- $theme_cfg = '/theme.cfg.php';
-
while (($f = readdir($handle)) !== false) {
debug_event('theme', "Checking $f", 5);
- $file = AmpConfig::get('prefix') . '/themes/' . $f;
- if (file_exists($file . $theme_cfg)) {
- debug_event('theme', "Loading $theme_cfg from $f", 5);
- $r = parse_ini_file($file . $theme_cfg);
- $r['path'] = $f;
- $results[$r['name']] = $r;
- } else {
- debug_event('theme', "$theme_cfg not found in $f", 5);
+ $cfg = get_theme($f);
+ if ($cfg !== null) {
+ $results[$cfg['name']] = $cfg;
}
} // end while directory
@@ -56,7 +49,6 @@ function get_themes()
ksort($results);
return $results;
-
} // get_themes
/*!
@@ -66,13 +58,35 @@ function get_themes()
*/
function get_theme($name)
{
- if (strlen($name) < 1) { return false; }
+ static $_mapcache = array();
+
+ if (strlen($name) < 1) {
+ return false;
+ }
+
+ $name = strtolower($name);
+
+ if (isset($_mapcache[$name])) {
+ return $_mapcache[$name];
+ }
$config_file = AmpConfig::get('prefix') . "/themes/" . $name . "/theme.cfg.php";
- $results = parse_ini_file($config_file);
- $results['path'] = $name;
+ if (file_exists($config_file)) {
+ $results = parse_ini_file($config_file);
+ $results['path'] = $name;
+ $results['base'] = explode(',', $results['base']);
+ $nbbases = count($results['base']);
+ for ($i = 0; $i < $nbbases; $i++) {
+ $results['base'][$i] = explode('|', $results['base'][$i]);
+ }
+ $results['colors'] = explode(',', $results['colors']);
+ } else {
+ debug_event('theme', $config_file . ' not found.', 3);
+ $results = null;
+ }
+ $_mapcache[$name] = $results;
+
return $results;
-
} // get_theme
/*!
@@ -82,10 +96,9 @@ function get_theme($name)
function get_theme_author($theme_name)
{
$theme_path = AmpConfig::get('prefix') . '/themes/' . $theme_name . '/theme.cfg.php';
- $results = read_config($theme_path);
+ $results = read_config($theme_path);
return $results['author'];
-
} // get_theme_author
/*!
@@ -101,5 +114,5 @@ function theme_exists($theme_name)
}
return true;
-
} // theme_exists
+
diff --git a/sources/lib/ui.lib.php b/sources/lib/ui.lib.php
index 48843a4..fc4ad92 100644
--- a/sources/lib/ui.lib.php
+++ b/sources/lib/ui.lib.php
@@ -5,22 +5,25 @@
* This contains functions that are generic, and display information
* things like a confirmation box, etc and so forth
*
+ */
+
+/**
*
- * LICENSE: GNU General Public License, version 2 (GPLv2)
+ * LICENSE: GNU Affero General Public License, version 3 (AGPLv3)
* Copyright 2001 - 2015 Ampache.org
*
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License v2
- * as published by the Free Software Foundation.
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * GNU Affero General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*
*/
@@ -43,9 +46,22 @@ function show_confirmation($title,$text,$next_url,$cancel=0,$form_name='confirma
$path = AmpConfig::get('web_path') . "/$next_url";
}
- require AmpConfig::get('prefix') . '/templates/show_confirmation.inc.php';
+ require AmpConfig::get('prefix') . UI::find_template('show_confirmation.inc.php');
} // show_confirmation
+function catalog_worker($action, $catalogs = null, $options = null)
+{
+ if (AmpConfig::get('ajax_load')) {
+ $sse_url = AmpConfig::get('web_path') . "/server/sse.server.php?worker=catalog&action=" . $action . "&catalogs=" . urlencode(json_encode($catalogs));
+ if ($options) {
+ $sse_url .= "&options=" . urlencode(json_encode($_POST));
+ }
+ sse_worker($sse_url);
+ } else {
+ Catalog::process_action($action, $catalogs, $options);
+ }
+}
+
function sse_worker($url)
{
echo '\n";
}
-
} // show_album_select
/**
@@ -262,7 +273,7 @@ function show_artist_select($name='artist', $artist_id=0, $allow_add=false, $son
$key = $name . "_select_c" . ++$artist_id_cnt;
}
- $sql = "SELECT `id`, `name`, `prefix` FROM `artist` ";
+ $sql = "SELECT `id`, `name`, `prefix` FROM `artist` ";
$params = array();
if ($user) {
$sql .= "WHERE `user` = ? ";
@@ -270,7 +281,7 @@ function show_artist_select($name='artist', $artist_id=0, $allow_add=false, $son
}
$sql .= "ORDER BY `name`";
$db_results = Dba::read($sql, $params);
- $count = Dba::num_rows($db_results);
+ $count = Dba::num_rows($db_results);
echo "\n";
-
} // show_tvshow_select
function show_tvshow_season_select($name='tvshow_season', $season_id, $allow_add=false, $video_id=0, $allow_none=false)
{
- if (!$season_id)
+ if (!$season_id) {
return false;
+ }
$season = new TVShow_Season($season_id);
static $season_id_cnt = 0;
@@ -365,7 +373,7 @@ function show_tvshow_season_select($name='tvshow_season', $season_id, $allow_add
echo "\t
\n";
}
- $sql = "SELECT `id`, `season_number` FROM `tvshow_season` WHERE `tvshow` = ? ORDER BY `season_number`";
+ $sql = "SELECT `id`, `season_number` FROM `tvshow_season` WHERE `tvshow` = ? ORDER BY `season_number`";
$db_results = Dba::read($sql, array($season->tvshow));
while ($r = Dba::fetch_assoc($db_results)) {
@@ -375,7 +383,6 @@ function show_tvshow_season_select($name='tvshow_season', $season_id, $allow_add
}
echo "\t