diff --git a/bin/fixreleasenames.php b/bin/fixreleasenames.php index cdcc74d7b..f1d545f93 100644 --- a/bin/fixreleasenames.php +++ b/bin/fixreleasenames.php @@ -1,13 +1,9 @@ processTv($argv[1]); -} +} \ No newline at end of file diff --git a/bin/update_binaries.php b/bin/update_binaries.php index eb6091f4f..b934f6006 100644 --- a/bin/update_binaries.php +++ b/bin/update_binaries.php @@ -1,10 +1,8 @@ sqlpatch; $patched = 0; $patches = array(); - $db = new DB(); + $db = new newznab\db\DB(); $backedup = false; $c = new ColorCLI(); $DIR = dirname (__FILE__); diff --git a/lib/copy_this/autoloaders.php b/lib/copy_this/autoloaders.php new file mode 100644 index 000000000..2c4dba800 --- /dev/null +++ b/lib/copy_this/autoloaders.php @@ -0,0 +1,29 @@ +. + * @author niel + * @copyright 2014 nZEDb + */ + +require_once NN_CORE . 'autoloader.php'; +require_once NN_LIB . 'autoloader.php'; + +require_once NN_WWW . '/SPLClassLoader.php'; + +$paths = array(NN_ROOT, NN_WWW . 'pages', SMARTY_DIR, SMARTY_DIR . 'plugins', SMARTY_DIR . 'sysplugins'); +$classLoader = new \SplClassLoader(null, $paths); +$classLoader->register(); \ No newline at end of file diff --git a/lib/copy_this/www/lib/amazon.php b/lib/copy_this/libs/AmazonProductAPI.php similarity index 100% rename from lib/copy_this/www/lib/amazon.php rename to lib/copy_this/libs/AmazonProductAPI.php diff --git a/lib/copy_this/www/lib/GiantBombAPI.php b/lib/copy_this/libs/GiantBombAPI.php similarity index 100% rename from lib/copy_this/www/lib/GiantBombAPI.php rename to lib/copy_this/libs/GiantBombAPI.php diff --git a/lib/copy_this/www/lib/Net_NNTP/LICENSE b/lib/copy_this/libs/Net_NNTP/LICENSE similarity index 100% rename from lib/copy_this/www/lib/Net_NNTP/LICENSE rename to lib/copy_this/libs/Net_NNTP/LICENSE diff --git a/lib/copy_this/www/lib/Net_NNTP/NNTP/Client.php b/lib/copy_this/libs/Net_NNTP/NNTP/Client.php similarity index 99% rename from lib/copy_this/www/lib/Net_NNTP/NNTP/Client.php rename to lib/copy_this/libs/Net_NNTP/NNTP/Client.php index 8ca7b96f0..96a7ab743 100644 --- a/lib/copy_this/www/lib/Net_NNTP/NNTP/Client.php +++ b/lib/copy_this/libs/Net_NNTP/NNTP/Client.php @@ -1388,6 +1388,4 @@ class Net_NNTP_Client extends Net_NNTP_Protocol_Client return $this->getReferences($first . '-' . $last); } -} - -?> \ No newline at end of file +} \ No newline at end of file diff --git a/lib/copy_this/www/lib/Net_NNTP/NNTP/Protocol/Client.php b/lib/copy_this/libs/Net_NNTP/NNTP/Protocol/Client.php similarity index 100% rename from lib/copy_this/www/lib/Net_NNTP/NNTP/Protocol/Client.php rename to lib/copy_this/libs/Net_NNTP/NNTP/Protocol/Client.php diff --git a/lib/copy_this/www/lib/Net_NNTP/NNTP/Protocol/Responsecode.php b/lib/copy_this/libs/Net_NNTP/NNTP/Protocol/Responsecode.php similarity index 100% rename from lib/copy_this/www/lib/Net_NNTP/NNTP/Protocol/Responsecode.php rename to lib/copy_this/libs/Net_NNTP/NNTP/Protocol/Responsecode.php diff --git a/lib/PHPMailer/PHPMailerAutoload.php b/lib/copy_this/libs/PHPMailer/PHPMailerAutoload.php similarity index 100% rename from lib/PHPMailer/PHPMailerAutoload.php rename to lib/copy_this/libs/PHPMailer/PHPMailerAutoload.php diff --git a/lib/PHPMailer/VERSION b/lib/copy_this/libs/PHPMailer/VERSION similarity index 100% rename from lib/PHPMailer/VERSION rename to lib/copy_this/libs/PHPMailer/VERSION diff --git a/lib/PHPMailer/class.phpmailer.php b/lib/copy_this/libs/PHPMailer/class.phpmailer.php similarity index 100% rename from lib/PHPMailer/class.phpmailer.php rename to lib/copy_this/libs/PHPMailer/class.phpmailer.php diff --git a/lib/PHPMailer/class.pop3.php b/lib/copy_this/libs/PHPMailer/class.pop3.php similarity index 100% rename from lib/PHPMailer/class.pop3.php rename to lib/copy_this/libs/PHPMailer/class.pop3.php diff --git a/lib/PHPMailer/class.smtp.php b/lib/copy_this/libs/PHPMailer/class.smtp.php similarity index 100% rename from lib/PHPMailer/class.smtp.php rename to lib/copy_this/libs/PHPMailer/class.smtp.php diff --git a/lib/PHPMailer/extras/EasyPeasyICS.php b/lib/copy_this/libs/PHPMailer/extras/EasyPeasyICS.php similarity index 100% rename from lib/PHPMailer/extras/EasyPeasyICS.php rename to lib/copy_this/libs/PHPMailer/extras/EasyPeasyICS.php diff --git a/lib/PHPMailer/extras/README.md b/lib/copy_this/libs/PHPMailer/extras/README.md similarity index 100% rename from lib/PHPMailer/extras/README.md rename to lib/copy_this/libs/PHPMailer/extras/README.md diff --git a/lib/PHPMailer/extras/class.html2text.php b/lib/copy_this/libs/PHPMailer/extras/class.html2text.php similarity index 100% rename from lib/PHPMailer/extras/class.html2text.php rename to lib/copy_this/libs/PHPMailer/extras/class.html2text.php diff --git a/lib/PHPMailer/extras/htmlfilter.php b/lib/copy_this/libs/PHPMailer/extras/htmlfilter.php similarity index 100% rename from lib/PHPMailer/extras/htmlfilter.php rename to lib/copy_this/libs/PHPMailer/extras/htmlfilter.php diff --git a/lib/PHPMailer/extras/ntlm_sasl_client.php b/lib/copy_this/libs/PHPMailer/extras/ntlm_sasl_client.php similarity index 99% rename from lib/PHPMailer/extras/ntlm_sasl_client.php rename to lib/copy_this/libs/PHPMailer/extras/ntlm_sasl_client.php index b21ccce0e..ac9689e6f 100644 --- a/lib/PHPMailer/extras/ntlm_sasl_client.php +++ b/lib/copy_this/libs/PHPMailer/extras/ntlm_sasl_client.php @@ -180,6 +180,4 @@ class ntlm_sasl_client_class } return(SASL_CONTINUE); } -}; - -?> \ No newline at end of file +}; \ No newline at end of file diff --git a/lib/copy_this/www/lib/TMDb.php b/lib/copy_this/libs/TMDb.php similarity index 100% rename from lib/copy_this/www/lib/TMDb.php rename to lib/copy_this/libs/TMDb.php diff --git a/lib/copy_this/libs/ZipFile.php b/lib/copy_this/libs/ZipFile.php new file mode 100644 index 000000000..42bb941d8 --- /dev/null +++ b/lib/copy_this/libs/ZipFile.php @@ -0,0 +1,191 @@ + + * + * http://www.zend.com/codex.php?id=470&single=1 + * by Denis125 + * + * a patch from Peter Listiak for last modified + * date and time of the compressed file + * + * Official ZIP file format: http://www.pkware.com/appnote.txt + * + * @access public + * @package phpMyAdmin + */ +class ZipFile +{ + /** + * Array to store compressed data + * + * @var array $datasec + */ + var $datasec = array(); + + /** + * Central directory + * + * @var array $ctrl_dir + */ + var $ctrl_dir = array(); + + /** + * End of central directory record + * + * @var string $eof_ctrl_dir + */ + var $eof_ctrl_dir = "\x50\x4b\x05\x06\x00\x00\x00\x00"; + + /** + * Last offset position + * + * @var integer $old_offset + */ + var $old_offset = 0; + + + /** + * Converts an Unix timestamp to a four byte DOS date and time format (date + * in high two bytes, time in low two bytes allowing magnitude comparison). + * + * @param integer the current Unix timestamp + * + * @return integer the current date in a four byte DOS format + * + * @access private + */ + function unix2DosTime($unixtime = 0) { + $timearray = ($unixtime == 0) ? getdate() : getdate($unixtime); + + if ($timearray['year'] < 1980) { + $timearray['year'] = 1980; + $timearray['mon'] = 1; + $timearray['mday'] = 1; + $timearray['hours'] = 0; + $timearray['minutes'] = 0; + $timearray['seconds'] = 0; + } // end if + + return (($timearray['year'] - 1980) << 25) | ($timearray['mon'] << 21) | ($timearray['mday'] << 16) | + ($timearray['hours'] << 11) | ($timearray['minutes'] << 5) | ($timearray['seconds'] >> 1); + } // end of the 'unix2DosTime()' method + + + /** + * Adds "file" to archive + * + * @param string file contents + * @param string name of the file in the archive (may contains the path) + * @param integer the current timestamp + * + * @access public + */ + function addFile($data, $name, $time = 0) + { + $name = str_replace('\\', '/', $name); + + $dtime = dechex($this->unix2DosTime($time)); + $hexdtime = '\x' . $dtime[6] . $dtime[7] + . '\x' . $dtime[4] . $dtime[5] + . '\x' . $dtime[2] . $dtime[3] + . '\x' . $dtime[0] . $dtime[1]; + eval('$hexdtime = "' . $hexdtime . '";'); + + $fr = "\x50\x4b\x03\x04"; + $fr .= "\x14\x00"; // ver needed to extract + $fr .= "\x00\x00"; // gen purpose bit flag + $fr .= "\x08\x00"; // compression method + $fr .= $hexdtime; // last mod time and date + + // "local file header" segment + $unc_len = strlen($data); + $crc = crc32($data); + $zdata = gzcompress($data); + $zdata = substr(substr($zdata, 0, strlen($zdata) - 4), 2); // fix crc bug + $c_len = strlen($zdata); + $fr .= pack('V', $crc); // crc32 + $fr .= pack('V', $c_len); // compressed filesize + $fr .= pack('V', $unc_len); // uncompressed filesize + $fr .= pack('v', strlen($name)); // length of filename + $fr .= pack('v', 0); // extra field length + $fr .= $name; + + // "file data" segment + $fr .= $zdata; + + // "data descriptor" segment (optional but necessary if archive is not + // served as file) + // nijel(2004-10-19): this seems not to be needed at all and causes + // problems in some cases (bug #1037737) + //$fr .= pack('V', $crc); // crc32 + //$fr .= pack('V', $c_len); // compressed filesize + //$fr .= pack('V', $unc_len); // uncompressed filesize + + // add this entry to array + $this -> datasec[] = $fr; + + // now add to central directory record + $cdrec = "\x50\x4b\x01\x02"; + $cdrec .= "\x00\x00"; // version made by + $cdrec .= "\x14\x00"; // version needed to extract + $cdrec .= "\x00\x00"; // gen purpose bit flag + $cdrec .= "\x08\x00"; // compression method + $cdrec .= $hexdtime; // last mod time & date + $cdrec .= pack('V', $crc); // crc32 + $cdrec .= pack('V', $c_len); // compressed filesize + $cdrec .= pack('V', $unc_len); // uncompressed filesize + $cdrec .= pack('v', strlen($name)); // length of filename + $cdrec .= pack('v', 0); // extra field length + $cdrec .= pack('v', 0); // file comment length + $cdrec .= pack('v', 0); // disk number start + $cdrec .= pack('v', 0); // internal file attributes + $cdrec .= pack('V', 32); // external file attributes - 'archive' bit set + + $cdrec .= pack('V', $this -> old_offset); // relative offset of local header + $this -> old_offset += strlen($fr); + + $cdrec .= $name; + + // optional extra field, file comment goes here + // save to central directory + $this -> ctrl_dir[] = $cdrec; + } // end of the 'addFile()' method + + + /** + * Dumps out file + * + * @return string the zipped file + * + * @access public + */ + function file() + { + $data = implode('', $this -> datasec); + $ctrldir = implode('', $this -> ctrl_dir); + + return + $data . + $ctrldir . + $this -> eof_ctrl_dir . + pack('v', sizeof($this -> ctrl_dir)) . // total # of entries "on this disk" + pack('v', sizeof($this -> ctrl_dir)) . // total # of entries overall + pack('V', strlen($ctrldir)) . // size of central dir + pack('V', strlen($data)) . // offset to start of central dir + "\x00\x00"; // .zip file comment length + } // end of the 'file()' method + +} diff --git a/lib/copy_this/libs/autoloader.php b/lib/copy_this/libs/autoloader.php new file mode 100644 index 000000000..f3ab3dc7a --- /dev/null +++ b/lib/copy_this/libs/autoloader.php @@ -0,0 +1,37 @@ +isDir() && !$fileInfo->isDot()) { + $file = $fileInfo->getPathname() . DIRECTORY_SEPARATOR . $filename; + if (file_exists($file) && is_readable($file)) { + require_once $file; + } + } + } + } + } +); \ No newline at end of file diff --git a/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/forkdaemon-php/LICENSE b/lib/copy_this/libs/forkdaemon-php/LICENSE similarity index 100% rename from lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/forkdaemon-php/LICENSE rename to lib/copy_this/libs/forkdaemon-php/LICENSE diff --git a/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/forkdaemon-php/README.md b/lib/copy_this/libs/forkdaemon-php/README.md similarity index 100% rename from lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/forkdaemon-php/README.md rename to lib/copy_this/libs/forkdaemon-php/README.md diff --git a/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/forkdaemon-php/composer.json b/lib/copy_this/libs/forkdaemon-php/composer.json similarity index 100% rename from lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/forkdaemon-php/composer.json rename to lib/copy_this/libs/forkdaemon-php/composer.json diff --git a/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/forkdaemon-php/examples/blocking.php b/lib/copy_this/libs/forkdaemon-php/examples/blocking.php similarity index 100% rename from lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/forkdaemon-php/examples/blocking.php rename to lib/copy_this/libs/forkdaemon-php/examples/blocking.php diff --git a/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/forkdaemon-php/examples/bucket.php b/lib/copy_this/libs/forkdaemon-php/examples/bucket.php similarity index 100% rename from lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/forkdaemon-php/examples/bucket.php rename to lib/copy_this/libs/forkdaemon-php/examples/bucket.php diff --git a/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/forkdaemon-php/examples/identifier.php b/lib/copy_this/libs/forkdaemon-php/examples/identifier.php similarity index 100% rename from lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/forkdaemon-php/examples/identifier.php rename to lib/copy_this/libs/forkdaemon-php/examples/identifier.php diff --git a/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/forkdaemon-php/examples/nonblocking.php b/lib/copy_this/libs/forkdaemon-php/examples/nonblocking.php similarity index 100% rename from lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/forkdaemon-php/examples/nonblocking.php rename to lib/copy_this/libs/forkdaemon-php/examples/nonblocking.php diff --git a/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/forkdaemon-php/examples/result_callback.php b/lib/copy_this/libs/forkdaemon-php/examples/result_callback.php similarity index 100% rename from lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/forkdaemon-php/examples/result_callback.php rename to lib/copy_this/libs/forkdaemon-php/examples/result_callback.php diff --git a/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/forkdaemon-php/examples/result_deferred.php b/lib/copy_this/libs/forkdaemon-php/examples/result_deferred.php similarity index 100% rename from lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/forkdaemon-php/examples/result_deferred.php rename to lib/copy_this/libs/forkdaemon-php/examples/result_deferred.php diff --git a/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/forkdaemon-php/fork_daemon.php b/lib/copy_this/libs/forkdaemon-php/fork_daemon.php similarity index 100% rename from lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/forkdaemon-php/fork_daemon.php rename to lib/copy_this/libs/forkdaemon-php/fork_daemon.php diff --git a/lib/getid3/.gitattributes b/lib/copy_this/libs/getid3/.gitattributes similarity index 100% rename from lib/getid3/.gitattributes rename to lib/copy_this/libs/getid3/.gitattributes diff --git a/lib/getid3/.gitignore b/lib/copy_this/libs/getid3/.gitignore similarity index 100% rename from lib/getid3/.gitignore rename to lib/copy_this/libs/getid3/.gitignore diff --git a/lib/getid3/changelog.txt b/lib/copy_this/libs/getid3/changelog.txt similarity index 100% rename from lib/getid3/changelog.txt rename to lib/copy_this/libs/getid3/changelog.txt diff --git a/lib/getid3/demos/demo.audioinfo.class.php b/lib/copy_this/libs/getid3/demos/demo.audioinfo.class.php similarity index 100% rename from lib/getid3/demos/demo.audioinfo.class.php rename to lib/copy_this/libs/getid3/demos/demo.audioinfo.class.php diff --git a/lib/getid3/demos/demo.basic.php b/lib/copy_this/libs/getid3/demos/demo.basic.php similarity index 100% rename from lib/getid3/demos/demo.basic.php rename to lib/copy_this/libs/getid3/demos/demo.basic.php diff --git a/lib/getid3/demos/demo.browse.php b/lib/copy_this/libs/getid3/demos/demo.browse.php similarity index 100% rename from lib/getid3/demos/demo.browse.php rename to lib/copy_this/libs/getid3/demos/demo.browse.php diff --git a/lib/getid3/demos/demo.cache.dbm.php b/lib/copy_this/libs/getid3/demos/demo.cache.dbm.php similarity index 100% rename from lib/getid3/demos/demo.cache.dbm.php rename to lib/copy_this/libs/getid3/demos/demo.cache.dbm.php diff --git a/lib/getid3/demos/demo.cache.mysql.php b/lib/copy_this/libs/getid3/demos/demo.cache.mysql.php similarity index 100% rename from lib/getid3/demos/demo.cache.mysql.php rename to lib/copy_this/libs/getid3/demos/demo.cache.mysql.php diff --git a/lib/getid3/demos/demo.joinmp3.php b/lib/copy_this/libs/getid3/demos/demo.joinmp3.php similarity index 100% rename from lib/getid3/demos/demo.joinmp3.php rename to lib/copy_this/libs/getid3/demos/demo.joinmp3.php diff --git a/lib/getid3/demos/demo.mimeonly.php b/lib/copy_this/libs/getid3/demos/demo.mimeonly.php similarity index 100% rename from lib/getid3/demos/demo.mimeonly.php rename to lib/copy_this/libs/getid3/demos/demo.mimeonly.php diff --git a/lib/getid3/demos/demo.mp3header.php b/lib/copy_this/libs/getid3/demos/demo.mp3header.php similarity index 100% rename from lib/getid3/demos/demo.mp3header.php rename to lib/copy_this/libs/getid3/demos/demo.mp3header.php diff --git a/lib/getid3/demos/demo.mysql.php b/lib/copy_this/libs/getid3/demos/demo.mysql.php similarity index 100% rename from lib/getid3/demos/demo.mysql.php rename to lib/copy_this/libs/getid3/demos/demo.mysql.php diff --git a/lib/getid3/demos/demo.simple.php b/lib/copy_this/libs/getid3/demos/demo.simple.php similarity index 100% rename from lib/getid3/demos/demo.simple.php rename to lib/copy_this/libs/getid3/demos/demo.simple.php diff --git a/lib/getid3/demos/demo.simple.write.php b/lib/copy_this/libs/getid3/demos/demo.simple.write.php similarity index 100% rename from lib/getid3/demos/demo.simple.write.php rename to lib/copy_this/libs/getid3/demos/demo.simple.write.php diff --git a/lib/getid3/demos/demo.write.php b/lib/copy_this/libs/getid3/demos/demo.write.php similarity index 100% rename from lib/getid3/demos/demo.write.php rename to lib/copy_this/libs/getid3/demos/demo.write.php diff --git a/lib/getid3/demos/demo.zip.php b/lib/copy_this/libs/getid3/demos/demo.zip.php similarity index 100% rename from lib/getid3/demos/demo.zip.php rename to lib/copy_this/libs/getid3/demos/demo.zip.php diff --git a/lib/getid3/demos/getid3.css b/lib/copy_this/libs/getid3/demos/getid3.css similarity index 100% rename from lib/getid3/demos/getid3.css rename to lib/copy_this/libs/getid3/demos/getid3.css diff --git a/lib/getid3/demos/getid3.demo.dirscan.php b/lib/copy_this/libs/getid3/demos/getid3.demo.dirscan.php similarity index 100% rename from lib/getid3/demos/getid3.demo.dirscan.php rename to lib/copy_this/libs/getid3/demos/getid3.demo.dirscan.php diff --git a/lib/getid3/demos/index.php b/lib/copy_this/libs/getid3/demos/index.php similarity index 100% rename from lib/getid3/demos/index.php rename to lib/copy_this/libs/getid3/demos/index.php diff --git a/lib/getid3/dependencies.txt b/lib/copy_this/libs/getid3/dependencies.txt similarity index 100% rename from lib/getid3/dependencies.txt rename to lib/copy_this/libs/getid3/dependencies.txt diff --git a/lib/getid3/getID3-1.9.7.readme.txt b/lib/copy_this/libs/getid3/getID3-1.9.7.readme.txt similarity index 100% rename from lib/getid3/getID3-1.9.7.readme.txt rename to lib/copy_this/libs/getid3/getID3-1.9.7.readme.txt diff --git a/lib/getid3/getid3/extension.cache.dbm.php b/lib/copy_this/libs/getid3/getid3/extension.cache.dbm.php similarity index 100% rename from lib/getid3/getid3/extension.cache.dbm.php rename to lib/copy_this/libs/getid3/getid3/extension.cache.dbm.php diff --git a/lib/getid3/getid3/extension.cache.mysql.php b/lib/copy_this/libs/getid3/getid3/extension.cache.mysql.php similarity index 100% rename from lib/getid3/getid3/extension.cache.mysql.php rename to lib/copy_this/libs/getid3/getid3/extension.cache.mysql.php diff --git a/lib/getid3/getid3/extension.cache.sqlite3.php b/lib/copy_this/libs/getid3/getid3/extension.cache.sqlite3.php similarity index 100% rename from lib/getid3/getid3/extension.cache.sqlite3.php rename to lib/copy_this/libs/getid3/getid3/extension.cache.sqlite3.php diff --git a/lib/getid3/getid3/getid3.lib.php b/lib/copy_this/libs/getid3/getid3/getid3.lib.php similarity index 99% rename from lib/getid3/getid3/getid3.lib.php rename to lib/copy_this/libs/getid3/getid3/getid3.lib.php index 54008194a..b44f99eac 100644 --- a/lib/getid3/getid3/getid3.lib.php +++ b/lib/copy_this/libs/getid3/getid3/getid3.lib.php @@ -603,7 +603,7 @@ class getid3_lib if (empty($tempdir)) { // yes this is ugly, feel free to suggest a better way - require_once(dirname(__FILE__).'/getid3.php'); + require_once(dirname(__FILE__) . '/getid3.php'); $getid3_temp = new getID3(); $tempdir = $getid3_temp->tempdir; unset($getid3_temp); @@ -1138,7 +1138,7 @@ class getid3_lib static $tempdir = ''; if (empty($tempdir)) { // yes this is ugly, feel free to suggest a better way - require_once(dirname(__FILE__).'/getid3.php'); + require_once(dirname(__FILE__) . '/getid3.php'); $getid3_temp = new getID3(); $tempdir = $getid3_temp->tempdir; unset($getid3_temp); diff --git a/lib/getid3/getid3/getid3.php b/lib/copy_this/libs/getid3/getid3/getid3.php similarity index 99% rename from lib/getid3/getid3/getid3.php rename to lib/copy_this/libs/getid3/getid3/getid3.php index e5dd4df1f..83a98bf71 100644 --- a/lib/getid3/getid3/getid3.php +++ b/lib/copy_this/libs/getid3/getid3/getid3.php @@ -160,7 +160,7 @@ class getID3 } // Load support library - if (!include_once(GETID3_INCLUDEPATH.'getid3.lib.php')) { + if (!include_once(GETID3_INCLUDEPATH . 'getid3.lib.php')) { $this->startup_error .= 'getid3.lib.php is missing or corrupt'; } diff --git a/lib/getid3/getid3/module.archive.gzip.php b/lib/copy_this/libs/getid3/getid3/module.archive.gzip.php similarity index 100% rename from lib/getid3/getid3/module.archive.gzip.php rename to lib/copy_this/libs/getid3/getid3/module.archive.gzip.php diff --git a/lib/getid3/getid3/module.archive.rar.php b/lib/copy_this/libs/getid3/getid3/module.archive.rar.php similarity index 100% rename from lib/getid3/getid3/module.archive.rar.php rename to lib/copy_this/libs/getid3/getid3/module.archive.rar.php diff --git a/lib/getid3/getid3/module.archive.szip.php b/lib/copy_this/libs/getid3/getid3/module.archive.szip.php similarity index 100% rename from lib/getid3/getid3/module.archive.szip.php rename to lib/copy_this/libs/getid3/getid3/module.archive.szip.php diff --git a/lib/getid3/getid3/module.archive.tar.php b/lib/copy_this/libs/getid3/getid3/module.archive.tar.php similarity index 100% rename from lib/getid3/getid3/module.archive.tar.php rename to lib/copy_this/libs/getid3/getid3/module.archive.tar.php diff --git a/lib/getid3/getid3/module.archive.zip.php b/lib/copy_this/libs/getid3/getid3/module.archive.zip.php similarity index 100% rename from lib/getid3/getid3/module.archive.zip.php rename to lib/copy_this/libs/getid3/getid3/module.archive.zip.php diff --git a/lib/getid3/getid3/module.audio-video.asf.php b/lib/copy_this/libs/getid3/getid3/module.audio-video.asf.php similarity index 100% rename from lib/getid3/getid3/module.audio-video.asf.php rename to lib/copy_this/libs/getid3/getid3/module.audio-video.asf.php diff --git a/lib/getid3/getid3/module.audio-video.bink.php b/lib/copy_this/libs/getid3/getid3/module.audio-video.bink.php similarity index 100% rename from lib/getid3/getid3/module.audio-video.bink.php rename to lib/copy_this/libs/getid3/getid3/module.audio-video.bink.php diff --git a/lib/getid3/getid3/module.audio-video.flv.php b/lib/copy_this/libs/getid3/getid3/module.audio-video.flv.php similarity index 100% rename from lib/getid3/getid3/module.audio-video.flv.php rename to lib/copy_this/libs/getid3/getid3/module.audio-video.flv.php diff --git a/lib/getid3/getid3/module.audio-video.matroska.php b/lib/copy_this/libs/getid3/getid3/module.audio-video.matroska.php similarity index 100% rename from lib/getid3/getid3/module.audio-video.matroska.php rename to lib/copy_this/libs/getid3/getid3/module.audio-video.matroska.php diff --git a/lib/getid3/getid3/module.audio-video.mpeg.php b/lib/copy_this/libs/getid3/getid3/module.audio-video.mpeg.php similarity index 100% rename from lib/getid3/getid3/module.audio-video.mpeg.php rename to lib/copy_this/libs/getid3/getid3/module.audio-video.mpeg.php diff --git a/lib/getid3/getid3/module.audio-video.nsv.php b/lib/copy_this/libs/getid3/getid3/module.audio-video.nsv.php similarity index 100% rename from lib/getid3/getid3/module.audio-video.nsv.php rename to lib/copy_this/libs/getid3/getid3/module.audio-video.nsv.php diff --git a/lib/getid3/getid3/module.audio-video.quicktime.php b/lib/copy_this/libs/getid3/getid3/module.audio-video.quicktime.php similarity index 100% rename from lib/getid3/getid3/module.audio-video.quicktime.php rename to lib/copy_this/libs/getid3/getid3/module.audio-video.quicktime.php diff --git a/lib/getid3/getid3/module.audio-video.real.php b/lib/copy_this/libs/getid3/getid3/module.audio-video.real.php similarity index 100% rename from lib/getid3/getid3/module.audio-video.real.php rename to lib/copy_this/libs/getid3/getid3/module.audio-video.real.php diff --git a/lib/getid3/getid3/module.audio-video.riff.php b/lib/copy_this/libs/getid3/getid3/module.audio-video.riff.php similarity index 100% rename from lib/getid3/getid3/module.audio-video.riff.php rename to lib/copy_this/libs/getid3/getid3/module.audio-video.riff.php diff --git a/lib/getid3/getid3/module.audio-video.swf.php b/lib/copy_this/libs/getid3/getid3/module.audio-video.swf.php similarity index 100% rename from lib/getid3/getid3/module.audio-video.swf.php rename to lib/copy_this/libs/getid3/getid3/module.audio-video.swf.php diff --git a/lib/getid3/getid3/module.audio-video.ts.php b/lib/copy_this/libs/getid3/getid3/module.audio-video.ts.php similarity index 100% rename from lib/getid3/getid3/module.audio-video.ts.php rename to lib/copy_this/libs/getid3/getid3/module.audio-video.ts.php diff --git a/lib/getid3/getid3/module.audio.aa.php b/lib/copy_this/libs/getid3/getid3/module.audio.aa.php similarity index 100% rename from lib/getid3/getid3/module.audio.aa.php rename to lib/copy_this/libs/getid3/getid3/module.audio.aa.php diff --git a/lib/getid3/getid3/module.audio.aac.php b/lib/copy_this/libs/getid3/getid3/module.audio.aac.php similarity index 100% rename from lib/getid3/getid3/module.audio.aac.php rename to lib/copy_this/libs/getid3/getid3/module.audio.aac.php diff --git a/lib/getid3/getid3/module.audio.ac3.php b/lib/copy_this/libs/getid3/getid3/module.audio.ac3.php similarity index 100% rename from lib/getid3/getid3/module.audio.ac3.php rename to lib/copy_this/libs/getid3/getid3/module.audio.ac3.php diff --git a/lib/getid3/getid3/module.audio.au.php b/lib/copy_this/libs/getid3/getid3/module.audio.au.php similarity index 100% rename from lib/getid3/getid3/module.audio.au.php rename to lib/copy_this/libs/getid3/getid3/module.audio.au.php diff --git a/lib/getid3/getid3/module.audio.avr.php b/lib/copy_this/libs/getid3/getid3/module.audio.avr.php similarity index 100% rename from lib/getid3/getid3/module.audio.avr.php rename to lib/copy_this/libs/getid3/getid3/module.audio.avr.php diff --git a/lib/getid3/getid3/module.audio.bonk.php b/lib/copy_this/libs/getid3/getid3/module.audio.bonk.php similarity index 100% rename from lib/getid3/getid3/module.audio.bonk.php rename to lib/copy_this/libs/getid3/getid3/module.audio.bonk.php diff --git a/lib/getid3/getid3/module.audio.dss.php b/lib/copy_this/libs/getid3/getid3/module.audio.dss.php similarity index 100% rename from lib/getid3/getid3/module.audio.dss.php rename to lib/copy_this/libs/getid3/getid3/module.audio.dss.php diff --git a/lib/getid3/getid3/module.audio.dts.php b/lib/copy_this/libs/getid3/getid3/module.audio.dts.php similarity index 100% rename from lib/getid3/getid3/module.audio.dts.php rename to lib/copy_this/libs/getid3/getid3/module.audio.dts.php diff --git a/lib/getid3/getid3/module.audio.flac.php b/lib/copy_this/libs/getid3/getid3/module.audio.flac.php similarity index 100% rename from lib/getid3/getid3/module.audio.flac.php rename to lib/copy_this/libs/getid3/getid3/module.audio.flac.php diff --git a/lib/getid3/getid3/module.audio.la.php b/lib/copy_this/libs/getid3/getid3/module.audio.la.php similarity index 100% rename from lib/getid3/getid3/module.audio.la.php rename to lib/copy_this/libs/getid3/getid3/module.audio.la.php diff --git a/lib/getid3/getid3/module.audio.lpac.php b/lib/copy_this/libs/getid3/getid3/module.audio.lpac.php similarity index 100% rename from lib/getid3/getid3/module.audio.lpac.php rename to lib/copy_this/libs/getid3/getid3/module.audio.lpac.php diff --git a/lib/getid3/getid3/module.audio.midi.php b/lib/copy_this/libs/getid3/getid3/module.audio.midi.php similarity index 100% rename from lib/getid3/getid3/module.audio.midi.php rename to lib/copy_this/libs/getid3/getid3/module.audio.midi.php diff --git a/lib/getid3/getid3/module.audio.mod.php b/lib/copy_this/libs/getid3/getid3/module.audio.mod.php similarity index 100% rename from lib/getid3/getid3/module.audio.mod.php rename to lib/copy_this/libs/getid3/getid3/module.audio.mod.php diff --git a/lib/getid3/getid3/module.audio.monkey.php b/lib/copy_this/libs/getid3/getid3/module.audio.monkey.php similarity index 100% rename from lib/getid3/getid3/module.audio.monkey.php rename to lib/copy_this/libs/getid3/getid3/module.audio.monkey.php diff --git a/lib/getid3/getid3/module.audio.mp3.php b/lib/copy_this/libs/getid3/getid3/module.audio.mp3.php similarity index 100% rename from lib/getid3/getid3/module.audio.mp3.php rename to lib/copy_this/libs/getid3/getid3/module.audio.mp3.php diff --git a/lib/getid3/getid3/module.audio.mpc.php b/lib/copy_this/libs/getid3/getid3/module.audio.mpc.php similarity index 100% rename from lib/getid3/getid3/module.audio.mpc.php rename to lib/copy_this/libs/getid3/getid3/module.audio.mpc.php diff --git a/lib/getid3/getid3/module.audio.ogg.php b/lib/copy_this/libs/getid3/getid3/module.audio.ogg.php similarity index 100% rename from lib/getid3/getid3/module.audio.ogg.php rename to lib/copy_this/libs/getid3/getid3/module.audio.ogg.php diff --git a/lib/getid3/getid3/module.audio.optimfrog.php b/lib/copy_this/libs/getid3/getid3/module.audio.optimfrog.php similarity index 100% rename from lib/getid3/getid3/module.audio.optimfrog.php rename to lib/copy_this/libs/getid3/getid3/module.audio.optimfrog.php diff --git a/lib/getid3/getid3/module.audio.rkau.php b/lib/copy_this/libs/getid3/getid3/module.audio.rkau.php similarity index 100% rename from lib/getid3/getid3/module.audio.rkau.php rename to lib/copy_this/libs/getid3/getid3/module.audio.rkau.php diff --git a/lib/getid3/getid3/module.audio.shorten.php b/lib/copy_this/libs/getid3/getid3/module.audio.shorten.php similarity index 100% rename from lib/getid3/getid3/module.audio.shorten.php rename to lib/copy_this/libs/getid3/getid3/module.audio.shorten.php diff --git a/lib/getid3/getid3/module.audio.tta.php b/lib/copy_this/libs/getid3/getid3/module.audio.tta.php similarity index 100% rename from lib/getid3/getid3/module.audio.tta.php rename to lib/copy_this/libs/getid3/getid3/module.audio.tta.php diff --git a/lib/getid3/getid3/module.audio.voc.php b/lib/copy_this/libs/getid3/getid3/module.audio.voc.php similarity index 100% rename from lib/getid3/getid3/module.audio.voc.php rename to lib/copy_this/libs/getid3/getid3/module.audio.voc.php diff --git a/lib/getid3/getid3/module.audio.vqf.php b/lib/copy_this/libs/getid3/getid3/module.audio.vqf.php similarity index 100% rename from lib/getid3/getid3/module.audio.vqf.php rename to lib/copy_this/libs/getid3/getid3/module.audio.vqf.php diff --git a/lib/getid3/getid3/module.audio.wavpack.php b/lib/copy_this/libs/getid3/getid3/module.audio.wavpack.php similarity index 100% rename from lib/getid3/getid3/module.audio.wavpack.php rename to lib/copy_this/libs/getid3/getid3/module.audio.wavpack.php diff --git a/lib/getid3/getid3/module.graphic.bmp.php b/lib/copy_this/libs/getid3/getid3/module.graphic.bmp.php similarity index 100% rename from lib/getid3/getid3/module.graphic.bmp.php rename to lib/copy_this/libs/getid3/getid3/module.graphic.bmp.php diff --git a/lib/getid3/getid3/module.graphic.efax.php b/lib/copy_this/libs/getid3/getid3/module.graphic.efax.php similarity index 100% rename from lib/getid3/getid3/module.graphic.efax.php rename to lib/copy_this/libs/getid3/getid3/module.graphic.efax.php diff --git a/lib/getid3/getid3/module.graphic.gif.php b/lib/copy_this/libs/getid3/getid3/module.graphic.gif.php similarity index 100% rename from lib/getid3/getid3/module.graphic.gif.php rename to lib/copy_this/libs/getid3/getid3/module.graphic.gif.php diff --git a/lib/getid3/getid3/module.graphic.jpg.php b/lib/copy_this/libs/getid3/getid3/module.graphic.jpg.php similarity index 100% rename from lib/getid3/getid3/module.graphic.jpg.php rename to lib/copy_this/libs/getid3/getid3/module.graphic.jpg.php diff --git a/lib/getid3/getid3/module.graphic.pcd.php b/lib/copy_this/libs/getid3/getid3/module.graphic.pcd.php similarity index 100% rename from lib/getid3/getid3/module.graphic.pcd.php rename to lib/copy_this/libs/getid3/getid3/module.graphic.pcd.php diff --git a/lib/getid3/getid3/module.graphic.png.php b/lib/copy_this/libs/getid3/getid3/module.graphic.png.php similarity index 100% rename from lib/getid3/getid3/module.graphic.png.php rename to lib/copy_this/libs/getid3/getid3/module.graphic.png.php diff --git a/lib/getid3/getid3/module.graphic.svg.php b/lib/copy_this/libs/getid3/getid3/module.graphic.svg.php similarity index 100% rename from lib/getid3/getid3/module.graphic.svg.php rename to lib/copy_this/libs/getid3/getid3/module.graphic.svg.php diff --git a/lib/getid3/getid3/module.graphic.tiff.php b/lib/copy_this/libs/getid3/getid3/module.graphic.tiff.php similarity index 100% rename from lib/getid3/getid3/module.graphic.tiff.php rename to lib/copy_this/libs/getid3/getid3/module.graphic.tiff.php diff --git a/lib/getid3/getid3/module.misc.cue.php b/lib/copy_this/libs/getid3/getid3/module.misc.cue.php similarity index 100% rename from lib/getid3/getid3/module.misc.cue.php rename to lib/copy_this/libs/getid3/getid3/module.misc.cue.php diff --git a/lib/getid3/getid3/module.misc.exe.php b/lib/copy_this/libs/getid3/getid3/module.misc.exe.php similarity index 100% rename from lib/getid3/getid3/module.misc.exe.php rename to lib/copy_this/libs/getid3/getid3/module.misc.exe.php diff --git a/lib/getid3/getid3/module.misc.iso.php b/lib/copy_this/libs/getid3/getid3/module.misc.iso.php similarity index 100% rename from lib/getid3/getid3/module.misc.iso.php rename to lib/copy_this/libs/getid3/getid3/module.misc.iso.php diff --git a/lib/getid3/getid3/module.misc.msoffice.php b/lib/copy_this/libs/getid3/getid3/module.misc.msoffice.php similarity index 100% rename from lib/getid3/getid3/module.misc.msoffice.php rename to lib/copy_this/libs/getid3/getid3/module.misc.msoffice.php diff --git a/lib/getid3/getid3/module.misc.par2.php b/lib/copy_this/libs/getid3/getid3/module.misc.par2.php similarity index 100% rename from lib/getid3/getid3/module.misc.par2.php rename to lib/copy_this/libs/getid3/getid3/module.misc.par2.php diff --git a/lib/getid3/getid3/module.misc.pdf.php b/lib/copy_this/libs/getid3/getid3/module.misc.pdf.php similarity index 100% rename from lib/getid3/getid3/module.misc.pdf.php rename to lib/copy_this/libs/getid3/getid3/module.misc.pdf.php diff --git a/lib/getid3/getid3/module.tag.apetag.php b/lib/copy_this/libs/getid3/getid3/module.tag.apetag.php similarity index 100% rename from lib/getid3/getid3/module.tag.apetag.php rename to lib/copy_this/libs/getid3/getid3/module.tag.apetag.php diff --git a/lib/getid3/getid3/module.tag.id3v1.php b/lib/copy_this/libs/getid3/getid3/module.tag.id3v1.php similarity index 100% rename from lib/getid3/getid3/module.tag.id3v1.php rename to lib/copy_this/libs/getid3/getid3/module.tag.id3v1.php diff --git a/lib/getid3/getid3/module.tag.id3v2.php b/lib/copy_this/libs/getid3/getid3/module.tag.id3v2.php similarity index 100% rename from lib/getid3/getid3/module.tag.id3v2.php rename to lib/copy_this/libs/getid3/getid3/module.tag.id3v2.php diff --git a/lib/getid3/getid3/module.tag.lyrics3.php b/lib/copy_this/libs/getid3/getid3/module.tag.lyrics3.php similarity index 100% rename from lib/getid3/getid3/module.tag.lyrics3.php rename to lib/copy_this/libs/getid3/getid3/module.tag.lyrics3.php diff --git a/lib/getid3/getid3/module.tag.xmp.php b/lib/copy_this/libs/getid3/getid3/module.tag.xmp.php similarity index 100% rename from lib/getid3/getid3/module.tag.xmp.php rename to lib/copy_this/libs/getid3/getid3/module.tag.xmp.php diff --git a/lib/getid3/getid3/write.apetag.php b/lib/copy_this/libs/getid3/getid3/write.apetag.php similarity index 100% rename from lib/getid3/getid3/write.apetag.php rename to lib/copy_this/libs/getid3/getid3/write.apetag.php diff --git a/lib/getid3/getid3/write.id3v1.php b/lib/copy_this/libs/getid3/getid3/write.id3v1.php similarity index 100% rename from lib/getid3/getid3/write.id3v1.php rename to lib/copy_this/libs/getid3/getid3/write.id3v1.php diff --git a/lib/getid3/getid3/write.id3v2.php b/lib/copy_this/libs/getid3/getid3/write.id3v2.php similarity index 100% rename from lib/getid3/getid3/write.id3v2.php rename to lib/copy_this/libs/getid3/getid3/write.id3v2.php diff --git a/lib/getid3/getid3/write.lyrics3.php b/lib/copy_this/libs/getid3/getid3/write.lyrics3.php similarity index 100% rename from lib/getid3/getid3/write.lyrics3.php rename to lib/copy_this/libs/getid3/getid3/write.lyrics3.php diff --git a/lib/getid3/getid3/write.metaflac.php b/lib/copy_this/libs/getid3/getid3/write.metaflac.php similarity index 100% rename from lib/getid3/getid3/write.metaflac.php rename to lib/copy_this/libs/getid3/getid3/write.metaflac.php diff --git a/lib/getid3/getid3/write.php b/lib/copy_this/libs/getid3/getid3/write.php similarity index 99% rename from lib/getid3/getid3/write.php rename to lib/copy_this/libs/getid3/getid3/write.php index 3a7f1974d..080e9a099 100644 --- a/lib/getid3/getid3/write.php +++ b/lib/copy_this/libs/getid3/getid3/write.php @@ -22,7 +22,7 @@ if (!defined('GETID3_INCLUDEPATH')) { throw new Exception('getid3.php MUST be included before calling getid3_writetags'); } -if (!include_once(GETID3_INCLUDEPATH.'getid3.lib.php')) { +if (!include_once(GETID3_INCLUDEPATH . 'getid3.lib.php')) { throw new Exception('write.php depends on getid3.lib.php, which is missing.'); } diff --git a/lib/getid3/getid3/write.real.php b/lib/copy_this/libs/getid3/getid3/write.real.php similarity index 100% rename from lib/getid3/getid3/write.real.php rename to lib/copy_this/libs/getid3/getid3/write.real.php diff --git a/lib/getid3/getid3/write.vorbiscomment.php b/lib/copy_this/libs/getid3/getid3/write.vorbiscomment.php similarity index 100% rename from lib/getid3/getid3/write.vorbiscomment.php rename to lib/copy_this/libs/getid3/getid3/write.vorbiscomment.php diff --git a/lib/getid3/helperapps/cygwin1.dll b/lib/copy_this/libs/getid3/helperapps/cygwin1.dll similarity index 100% rename from lib/getid3/helperapps/cygwin1.dll rename to lib/copy_this/libs/getid3/helperapps/cygwin1.dll diff --git a/lib/getid3/helperapps/head.exe b/lib/copy_this/libs/getid3/helperapps/head.exe similarity index 100% rename from lib/getid3/helperapps/head.exe rename to lib/copy_this/libs/getid3/helperapps/head.exe diff --git a/lib/getid3/helperapps/md5sum.exe b/lib/copy_this/libs/getid3/helperapps/md5sum.exe similarity index 100% rename from lib/getid3/helperapps/md5sum.exe rename to lib/copy_this/libs/getid3/helperapps/md5sum.exe diff --git a/lib/getid3/helperapps/metaflac.exe b/lib/copy_this/libs/getid3/helperapps/metaflac.exe similarity index 100% rename from lib/getid3/helperapps/metaflac.exe rename to lib/copy_this/libs/getid3/helperapps/metaflac.exe diff --git a/lib/getid3/helperapps/readme.helperapps.txt b/lib/copy_this/libs/getid3/helperapps/readme.helperapps.txt similarity index 100% rename from lib/getid3/helperapps/readme.helperapps.txt rename to lib/copy_this/libs/getid3/helperapps/readme.helperapps.txt diff --git a/lib/getid3/helperapps/sha1sum.exe b/lib/copy_this/libs/getid3/helperapps/sha1sum.exe similarity index 100% rename from lib/getid3/helperapps/sha1sum.exe rename to lib/copy_this/libs/getid3/helperapps/sha1sum.exe diff --git a/lib/getid3/helperapps/shorten.exe b/lib/copy_this/libs/getid3/helperapps/shorten.exe similarity index 100% rename from lib/getid3/helperapps/shorten.exe rename to lib/copy_this/libs/getid3/helperapps/shorten.exe diff --git a/lib/getid3/helperapps/tail.exe b/lib/copy_this/libs/getid3/helperapps/tail.exe similarity index 100% rename from lib/getid3/helperapps/tail.exe rename to lib/copy_this/libs/getid3/helperapps/tail.exe diff --git a/lib/getid3/helperapps/vorbiscomment.exe b/lib/copy_this/libs/getid3/helperapps/vorbiscomment.exe similarity index 100% rename from lib/getid3/helperapps/vorbiscomment.exe rename to lib/copy_this/libs/getid3/helperapps/vorbiscomment.exe diff --git a/lib/getid3/license.txt b/lib/copy_this/libs/getid3/license.txt similarity index 100% rename from lib/getid3/license.txt rename to lib/copy_this/libs/getid3/license.txt diff --git a/lib/getid3/licenses/licence.gpl-10.txt b/lib/copy_this/libs/getid3/licenses/licence.gpl-10.txt similarity index 100% rename from lib/getid3/licenses/licence.gpl-10.txt rename to lib/copy_this/libs/getid3/licenses/licence.gpl-10.txt diff --git a/lib/getid3/licenses/licence.gpl-20.txt b/lib/copy_this/libs/getid3/licenses/licence.gpl-20.txt similarity index 100% rename from lib/getid3/licenses/licence.gpl-20.txt rename to lib/copy_this/libs/getid3/licenses/licence.gpl-20.txt diff --git a/lib/getid3/licenses/licence.gpl-30.txt b/lib/copy_this/libs/getid3/licenses/licence.gpl-30.txt similarity index 100% rename from lib/getid3/licenses/licence.gpl-30.txt rename to lib/copy_this/libs/getid3/licenses/licence.gpl-30.txt diff --git a/lib/getid3/licenses/licence.lgpl-30.txt b/lib/copy_this/libs/getid3/licenses/licence.lgpl-30.txt similarity index 100% rename from lib/getid3/licenses/licence.lgpl-30.txt rename to lib/copy_this/libs/getid3/licenses/licence.lgpl-30.txt diff --git a/lib/getid3/licenses/licence.mpl-20.txt b/lib/copy_this/libs/getid3/licenses/licence.mpl-20.txt similarity index 100% rename from lib/getid3/licenses/licence.mpl-20.txt rename to lib/copy_this/libs/getid3/licenses/licence.mpl-20.txt diff --git a/lib/getid3/licenses/license.commercial.txt b/lib/copy_this/libs/getid3/licenses/license.commercial.txt similarity index 100% rename from lib/getid3/licenses/license.commercial.txt rename to lib/copy_this/libs/getid3/licenses/license.commercial.txt diff --git a/lib/getid3/structure.txt b/lib/copy_this/libs/getid3/structure.txt similarity index 100% rename from lib/getid3/structure.txt rename to lib/copy_this/libs/getid3/structure.txt diff --git a/lib/copy_this/libs/rarinfo/archiveinfo.php b/lib/copy_this/libs/rarinfo/archiveinfo.php new file mode 100644 index 000000000..76f54c6dc --- /dev/null +++ b/lib/copy_this/libs/rarinfo/archiveinfo.php @@ -0,0 +1,886 @@ + + * + * // Load the archive file or data + * $archive = new ArchiveInfo; + * $archive->open('./foo.rar'); // or $archive->setData($data); + * if ($archive->error) { + * echo "Error: {$archive->error}\n"; + * exit; + * } + * + * // Check the archive type + * if ($archive->type != ArchiveInfo::TYPE_RAR) { + * echo "Source is not a RAR archive\n"; + * // exit here or continue with duck typing + * } + * + * // Check encryption + * if (!empty($archive->isEncrypted)) { + * echo "Archive is password encrypted\n"; + * exit; + * } + * + * // List the contents of all archives recursively + * foreach ($archive->getArchiveFileList() as $file) { + * if (isset($file['error'])) { + * echo "Error: {$file['error']} (in: {$file['source']})\n"; + * continue; // skip recursion errors + * } + * if (!empty($file['pass'])) { + * echo "File is passworded: {$file['name']} (in: {$file['source']})\n"; + * continue; // skip encrypted files + * } + * if (empty($file['compressed'])) { + * echo "Extracting uncompressed file: {$file['name']} from: {$file['source']}\n"; + * $archive->saveFileData($file['name'], "./dir/{$file['name']}", $file['source']); + * // or $data = $archive->getFileData($file['name'], $file['source']); + * } + * } + * + * + * + * @author Hecks + * @copyright (c) 2010-2013 Hecks + * @license Modified BSD + * @version 2.3 + */ +class ArchiveInfo extends ArchiveReader +{ + /**#@+ + * Supported archive types. + */ + const TYPE_NONE = 0x0000; + const TYPE_RAR = 0x0002; + const TYPE_ZIP = 0x0004; + const TYPE_SRR = 0x0008; + const TYPE_SFV = 0x0010; + const TYPE_PAR2 = 0x0020; + const TYPE_SZIP = 0x0040; + + /**#@-*/ + + /** + * Source path label of the main archive. + */ + const MAIN_SOURCE = 'main'; + + /** + * The default list of the supported archive reader classes. + * @var array + */ + protected $readers = array( + self::TYPE_RAR => 'RarInfo', + self::TYPE_SRR => 'SrrInfo', + self::TYPE_PAR2 => 'Par2Info', + self::TYPE_ZIP => 'ZipInfo', + self::TYPE_SFV => 'SfvInfo', + self::TYPE_SZIP => 'SzipInfo', + ); + + /** + * The current archive file/data type. + * @var integer + */ + public $type = self::TYPE_NONE; + + /** + * Sets the list of supported archive reader classes for the current instance, + * overriding the defaults. The keys should be valid archive types: + * + * $archive->setReaders(array(ArchiveInfo::TYPE_RAR => 'RarInfo')); + * + * If $recursive is set to true, this list will also be used for all embedded + * archives as well. This can be a bit unpredictable, so use with caution, but + * it's a convenient way to swap in custom readers or change their order. + * + * @param array $readers list of reader classes keyed by archive type + * @param boolean $recursive apply list to all embedded archives? + * @return void + */ + public function setReaders(array $readers, $recursive=false) + { + $this->readers = $readers; + $this->inheritReaders = $recursive; + if ($recursive) { + $this->archives = array(); + } + } + + /** + * Sets the list of external clients configured for each reader type to allow + * extraction of compressed files. The keys should be valid archive types: + * + * $archive->setExternalClients(array( + * ArchiveInfo::TYPE_RAR => 'path_to_unrar_client', + * ArchiveInfo::TYPE_ZIP => 'path_to_unzip_client', + * )); + * + * Note that extracting embedded encrypted files is not currently supported + * due to recursion issues. + * + * @param array $clients list of external clients + * @return void + */ + public function setExternalClients(array $clients) + { + if ($this->reader && isset($clients[$this->type])) { + $this->reader->setExternalClient($clients[$this->type]); + } + + $this->externalClients = $clients; + $this->archives = array(); + if ($this->reader) { + unset($this->error); + } + } + + /** + * Sets the regex string (minus delimiters and brackets) for filtering valid + * archive extensions when inspecting archive contents recursively. This check + * can be disabled completely by setting the value to NULL. + * + * @param string $extensions the regex of archive file extensions + * @return void + */ + public function setArchiveExtensions($extensions) + { + $this->extensions = $extensions; + $this->archives = array(); + } + + /** + * Convenience method that outputs a summary list of the archive information, + * useful for pretty-printing. + * + * When called with $full set to true, this method will also return a nested + * summary of all the embedded archive contents in the 'archives' field, keyed + * to the archive filenames. + * + * @param boolean $full return a full summary? + * @return array archive summary + */ + public function getSummary($full=false) + { + $summary = array( + 'main_info' => isset($this->readers[$this->type]) ? $this->readers[$this->type] : 'Unknown', + 'main_type' => $this->type, + 'file_name' => $this->file, + 'file_size' => $this->fileSize, + 'data_size' => $this->dataSize, + 'use_range' => "{$this->start}-{$this->end}", + ); + if ($this->reader) { + $args = func_get_args(); + $summary += $this->__call('getSummary', $args); + } + if ($full && $this->containsArchive()) { + $summary['archives'] = $this->getArchiveList(true); // recursive + } + if ($this->tempFiles) { + $summary['temp_files'] = array_keys($this->tempFiles); + } + if ($this->error) { + $summary['error'] = $this->error; + } + return $summary; + } + + /** + * Returns a list of records for each of the files in the archive by delegation + * to the stored reader. + * + * @return array|boolean list of file records, or false if none are available + */ + public function getFileList() + { + if ($this->reader) { + $args = func_get_args(); + return $this->__call('getFileList', $args); + } + + return false; + } + + /** + * Returns a list of the parsed data found in the source in human-readable + * format (for debugging purposes only). + * + * @return array|boolean parsed data, or false if none available + */ + public function getParsedData() + { + switch ($this->type) { + case self::TYPE_RAR: + case self::TYPE_SRR: + return $this->reader->getBlocks(); + case self::TYPE_PAR2: + return $this->reader->getPackets(); + case self::TYPE_ZIP: + return $this->reader->getRecords(); + case self::TYPE_SZIP: + return $this->reader->getHeaders(); + case self::TYPE_SFV: + return $this->reader->getFileList(); + default: + return false; + } + } + + /** + * Returns the stored archive reader instance for the file/data type. + * + * @return ArchiveReader + */ + public function getReader() + { + return $this->reader; + } + + /** + * Determines whether the current archive type can contain other archives + * through which it can search recursively. + * + * @return boolean + */ + public function allowsRecursion() + { + return (bool) ($this->type & (self::TYPE_RAR | self::TYPE_ZIP | self::TYPE_SZIP)); + } + + /** + * Determines whether the current archive contains another archive. + * + * @return boolean + */ + public function containsArchive() + { + $this->getArchiveList(); + return !empty($this->archives); + } + + /** + * Determines whether the current reader can extract files using an external + * client. + * + * @return boolean + */ + public function canExtract() + { + return $this->reader && (!empty($this->externalClients[$this->type]) + || !empty($this->reader->externalClient)); + } + + /** + * Lists any embedded archives, either as raw ArchiveInfo objects or as file + * summaries, and caches the object list locally. The optional filtering of + * valid archive extensions can be disabled by first calling: + * + * $archive->setArchiveExtensions(null); + * + * This will mean that all files in the archive will be inspected, regardless + * of their extensions - less efficient, more paranoid & probably buggier ;) + * + * @param boolean $summary return file summaries? + * @return array|boolean list of stored objects/summaries, or false on error + */ + public function getArchiveList($summary=false) + { + if (!$this->reader || !$this->allowsRecursion()) + return false; + + if (empty($this->archives)) { + $extensions = !empty($this->extensions) ? "/^({$this->extensions})$/" : false; + foreach ($this->reader->getFileList() as $file) { + if ($extensions && !preg_match($extensions, pathinfo($file['name'], PATHINFO_EXTENSION))) + continue; + if (($archive = $this->getArchive($file['name'])) + && ($archive->type != self::TYPE_NONE || empty($archive->readers)) + ) { + $this->archives[$file['name']] = $archive; + } + } + if (!empty($this->externalClients)) { + $this->extractArchives(); + } + } + if ($summary) { + $ret = array(); + foreach ($this->archives as $name => $archive) { + $ret[$name] = $archive->getSummary(true); // recursive + } + return $ret; + } + + return $this->archives; + } + + /** + * Returns an ArchiveInfo object for an embedded archive file with the contents + * analyzed (initially without recursion). Calls to this method can also be + * chained together to navigate the tree, e.g.: + * + * $rar->getArchive('parent.rar')->getArchive('child.zip')->getFileList(); + * + * @param string $filename the embedded archive filename + * @return ArchiveInfo|boolean false if an object can't be returned + */ + public function getArchive($filename) + { + if (!$this->reader || !$this->allowsRecursion()) + return false; + + // Check the cache first + if (isset($this->archives[$filename])) + return $this->archives[$filename]; + + foreach ($this->reader->getFileList(true) as $file) { + if ($file['name'] == $filename && isset($file['range'])) { + + // Create the new archive object + $archive = new self; + $archive->externalClients = $this->externalClients; + $archive->extensions = $this->extensions; + if ($this->inheritReaders) { + $archive->setReaders($this->readers, true); + } + + // Extract any compressed data to a temporary file if supported + if ($this->canExtract() && !empty($file['compressed']) && empty($file['pass'])) { + list($hash, $temp) = $this->getTempFileName("{$file['name']}:{$file['range']}"); + if (!isset($this->tempFiles[$hash])) { + $this->reader->extractFile($file['name'], $temp); + @chmod($temp, 0777); + $this->tempFiles[$hash] = $temp; + } + if ($this->reader->error) { + $archive->error = $this->reader->error; + $archive->readers = array(); + } else { + $archive->open($temp, $this->isFragment); + $archive->isTemporary = true; + } + return $archive; + } + + // Otherwise we shouldn't process any files that are unreadable + if (!empty($file['compressed']) || !empty($file['pass'])) { + $archive->readers = array(); + } + + // Try to parse the raw source file/data + $range = explode('-', $file['range']); + if ($this->file) { + $archive->open($this->file, $this->isFragment, $range); + } else { + $archive->setData($this->data, $this->isFragment, $range); + } + + // Make error messages more specific + if (!empty($file['compressed'])) { + $archive->error = 'The archive is compressed and cannot be read'; + } + if (!empty($file['pass']) || !empty($archive->isEncrypted)) { + $archive->error = 'The archive is encrypted and cannot be read'; + } + + return $archive; + } + } + + // Something went wrong + return false; + } + + /** + * Provides the contents of the current archive in a flat list, optionally + * recursing through all embedded archives as well, with a 'source' field + * added to each item that includes the archive source path. + * + * If $all is set to true, the file lists of all the supported archive types + * will be merged in the flat list, not just those that allow recursion. This + * should be used with caution, as the output varies between readers and the + * only guaranteed results are: + * + * array('name' => '...', 'source' => '...') or: + * array('error' => '...', 'source' => '...') + * + * It's really just handy for inspecting all known file names in the laziest + * way possible, and not much more than that. + * + * @param boolean $recurse list all archive contents recursively? + * @param string $all include all supported archive file lists? + * @param string $source [ignore, for internal use only] + * @return array|boolean the flat archive file list, or false on error + */ + public function getArchiveFileList($recurse=true, $all=false, $source=null) + { + if (!$this->reader) {return false;} + $ret = array(); + + // Start with the main parent + if ($source == null) { + $source = self::MAIN_SOURCE; + if ($ret = $this->reader->getFileList()) { + $ret = $this->flattenFileList($ret, $source, $all); + } + } + + // Merge each archive file list + if ($recurse && $this->containsArchive()) { + foreach ($this->getArchiveList() as $name => $archive) { + + // Only include the file lists of types that allow recursion? + if (empty($archive->error) && !$all && !$archive->allowsRecursion()) + continue; + $branch = $source.' > '.$name; + + // We should append any errors + if ($archive->error || !($files = $archive->reader->getFileList())) { + $error = $archive->error ? $archive->error : 'No files found'; + $ret[] = array('error' => $error, 'source' => $branch); + continue; + } + + // Otherwise merge recursively + $ret = array_merge($ret, $this->flattenFileList($files, $branch, $all)); + if ($archive->containsArchive()) { + $ret = array_merge($ret, $archive->getArchiveFileList(true, $all, $branch)); + } + } + } + + return $ret; + } + + /** + * Retrieves the archive reader object described by the given source path string. + * + * @param string $source archive source path of the file + * @return ArchiveReader|boolean archive reader object, or false on error + */ + public function getArchiveFromSource($source) + { + $this->getArchiveFileList(true); + $source = explode(' > ', $source); + foreach ($source as $file) { + $archive = ($file == self::MAIN_SOURCE) ? $this : $archive->getArchive($file); + if (!$archive) {break;} + } + + return isset($archive) ? $archive : false; + } + + /** + * Retrieves the raw data for the given filename and optionally the archive + * source (e.g. 'main' or 'main > child.rar', etc.). + * + * @param string $filename name of the file to extract + * @param string $source archive source path of the file + * @return string|boolean file data, or false on error + */ + public function getFileData($filename, $source=self::MAIN_SOURCE) + { + // Check that a valid data source is available + if (!$this->reader || ($this->reader->data == '' && $this->reader->handle == null)) + return false; + + // Get the absolute start/end positions + if (!($info = $this->getFileInfo($filename, $source)) || empty($info['range'])) { + $in_source = $source ? " in: ({$source})" : ''; + $this->error = "Could not find file info for: ({$filename}){$in_source}"; + return false; + } + unset($this->error); + + return $this->reader->getRange(explode('-', $info['range'])); + } + + /** + * Saves the raw data for the given filename and optionally archive source path + * to the given destination (e.g. 'main' or 'main > child.rar', etc.). + * + * @param string $filename name of the file to extract + * @param string $destination full path of the file to create + * @param string $source archive source path of the file + * @return integer|boolean number of bytes saved or false on error + */ + public function saveFileData($filename, $destination, $source=self::MAIN_SOURCE) + { + // Check that a valid data source is available + if (!$this->reader || ($this->reader->data == '' && $this->reader->handle == null)) + return false; + + // Get the absolute start/end positions + if (!($info = $this->getFileInfo($filename, $source)) || empty($info['range'])) { + $in_source = $source ? " in: ({$source})" : ''; + $this->error = "Could not find file info for: ({$filename}){$in_source}"; + return false; + } + unset($this->error); + + return $this->reader->saveRange(explode('-', $info['range']), $destination); + } + + /** + * Extracts a compressed or encrypted file using one of the configured external + * clients, optionally returning the data or saving it to file. + * + * Note that this method will fail with uncompressed or unencrypted files in + * embedded archives - use getFileData() or saveFileData() instead. + * + * @param string $filename name of the file to extract + * @param string $destination full path of the file to create + * @param string $password password to use for decryption + * @param string $source archive source path of the file to extract + * @return mixed extracted data, number of bytes saved or false on error + */ + public function extractFile($filename, $destination=null, $password=null, $source=self::MAIN_SOURCE) + { + // Check that a valid reader is available + if (!($archive = $this->getArchiveFromSource($source)) || !($reader = $archive->reader)) { + $this->error = "Not a valid archive source: {$source}"; + return false; + } + if (!method_exists($reader, 'extractFile')) { + $this->error = get_class($reader).' does not support the extractFile() method'; + return false; + } + + // Get the result of the extraction + $result = $reader->extractFile($filename, $destination, $password); + if ($reader->error) { + $this->error = $reader->error; + return false; + } + unset($this->error); + + return $result; + } + + /** + * Class destructor, cleanly removes any archive reader references. + * + * @return void + */ + public function __destruct() + { + $this->reset(); + parent::__destruct(); + } + + /** + * Returns the position of the first archive marker/signature in the stored + * data or file by delegation to the stored reader. + * + * @return mixed Marker position, or false if marker is missing + */ + public function findMarker() + { + if ($this->reader) + return $this->reader->findMarker(); + + return false; + } + + /** + * Magic method for accessing the properties of the stored reader. + * + * @param string $name the property name + * @return mixed the property value + */ + public function __get($name) + { + if ($this->reader && isset($this->reader->$name)) + return $this->reader->$name; + + return parent::__get($name); + } + + /** + * Magic method for testing whether properties of the stored reader are set. + * Note that if called via empty(), if the method returns TRUE a second call + * is made to __get() to test if the actual value is false. + * + * @param string $name the property name + * @return boolean + */ + public function __isset($name) + { + if ($this->reader) + return isset($this->reader->$name); + + return false; + } + + /** + * Magic method for delegating method calls to the stored reader. + * + * @param string $method the method name + * @param array $args the method arguments + * @return mixed result of the delegated method call + * @throws BadMethodCallException + */ + public function __call($method, $args) + { + if (!$this->reader) + throw new BadMethodCallException(get_class($this)."::$method() is not defined"); + + switch (count($args)) { + case 0: + return $this->reader->$method(); + case 1: + return $this->reader->$method($args[0]); + case 2: + return $this->reader->$method($args[0], $args[1]); + case 3: + return $this->reader->$method($args[0], $args[1], $args[2]); + default: + return call_user_func_array(array($this->reader, $method), $args); + } + } + + /** + * The stored archive reader instance. + * @var ArchiveReader + */ + protected $reader; + + /** + * Cached list of any embedded archive objects. + * @var array + */ + protected $archives = array(); + + /** + * Should any embedded archives inherit the readers list from this instance? + * @var boolean + */ + protected $inheritReaders = false; + + /** + * List of any external clients to use for extraction. + * @var array + */ + protected $externalClients = array(); + + /** + * Is the current archive being processed from a temporary file? + * @var boolean + */ + protected $isTemporary = false; + + /** + * The regex for filtering any valid archive extensions. + * @var string + */ + protected $extensions = 'rar|r[0-9]+|zip|srr|par2|sfv|7z|[0-9]+'; + + /** + * Parses the source file/data by delegation to one of the configured readers, + * or returns false if the source is not a supported type. + * + * @return boolean false if parsing fails + */ + protected function analyze() + { + // Create a reader to handle the file/data + if ($this->createReader() === false || $this->findMarker() === false) { + $this->error = 'Source is not a supported archive type'; + $this->close(); + return false; + } + + // Delegate some properties to the reader + unset($this->markerPosition); + unset($this->fileCount); + unset($this->error); + + // Let the reader handle any files + if ($this->file) { + $this->close(); + } + + return true; + } + + /** + * Creates a reader instance for parsing the source file/data and stores it + * locally for any later delegation. + * + * Each reader in the configured order tries to parse the source file/data and + * find a valid marker/signature for its type. Where more than one marker is + * present - such as with embedded archives - the reader that finds the earliest + * marker will be used as the delegate. + * + * @return boolean false if no reader could parse the source + */ + protected function createReader() + { + $range = array($this->start, $this->end); + + foreach ($this->readers as $type => $class) { + + // Analyze the source with a new reader + $reader = new $class; + if ($this->file) { + $reader->open($this->file, $this->isFragment, $range); + } else { + $reader->setData($this->data, $this->isFragment, $range); + } + if ($reader->error) {continue;} + + // Store the reader with the earliest marker + if (($marker = $reader->findMarker()) !== false) { + $start = !isset($start) ? $marker : $start; + if ($marker <= $start) { + $start = $marker; + if (!empty($this->externalClients[$type])) { + $reader->setExternalClient($this->externalClients[$type]); + } + $this->reader = $reader; + $this->type = $type; + } + if ($start === 0) {break;} + } + } + + return isset($this->reader); + } + + /** + * Returns information for the given filename and optionally archive source + * in the current file/data. + * + * @param string $filename the filename to search + * @param string $source archive source path of the file + * @return array|boolean the file info or false on error + */ + protected function getFileInfo($filename, $source=self::MAIN_SOURCE) + { + if (strpos($source, self::MAIN_SOURCE) !== 0) { + $source = self::MAIN_SOURCE.' > '.$source; + } + foreach ($this->getArchiveFileList(true) as $file) { + if (!empty($file['name']) && empty($file['is_dir']) + && $file['name'] == $filename && $file['source'] == $source + ) { + return $file; + } + } + + return false; + } + + /** + * Helper method that flattens a file list that may have children, removes keys + * and re-indexes, then adds a source path field to each item. + * + * @param array $files the file list to flatten + * @param string $source the current source path info + * @param boolean $all should any child lists be included? + * @return array the flat file list + */ + protected function flattenFileList(array $files, $source, $all=false) + { + $files = array_values($files); + $children = array(); + foreach ($files as &$file) { + $file['source'] = $source; + if ($source != self::MAIN_SOURCE) { + unset($file['next_offset']); + } + if ($all && !empty($file['files'])) foreach ($file['files'] as $child) { + $child['source'] = $source.' > '.$file['name']; + unset($child['next_offset']); + $children[] = $child; + } + } + if (!empty($children)) { + $files = array_merge($files, $children); + } + + return $files; + } + + /** + * Extracts any embedded archives that contain compressed files using the + * configured external clients to allow recursive inspection and extraction. + * + * @return boolean false on error + */ + protected function extractArchives() + { + if (!$this->reader || !$this->canExtract()) + return false; + + foreach ($this->archives as $name => $archive) { + if ($archive->isTemporary || !$archive->canExtract()) + continue; + + if ($files = $archive->reader->getFileList()) foreach ($files as $file) { + if (!empty($file['compressed']) && empty($file['pass'])) { + list($hash, $temp) = $this->getTempFileName("{$name}:{$archive->start}-{$archive->end}"); + if (!isset($this->tempFiles[$hash])) { + $archive->reader->saveRange(array($archive->start, $archive->end), $temp); + @chmod($temp, 0777); + $this->tempFiles[$hash] = $temp; + } + $archive->open($temp, $this->isFragment); + $archive->isTemporary = true; + continue 2; + } + } + } + + return true; + } + + /** + * Resets the instance variables before parsing new data. + * + * @return void + */ + protected function reset() + { + $this->reader = null; + foreach ($this->archives as $archive) { + $archive->reset(); + } + parent::reset(); + $this->archives = array(); + $this->type = self::TYPE_NONE; + $this->isTemporary = false; + } + +} // End ArchiveInfo class diff --git a/lib/copy_this/www/lib/rarinfo/archivereader.php b/lib/copy_this/libs/rarinfo/archivereader.php similarity index 77% rename from lib/copy_this/www/lib/rarinfo/archivereader.php rename to lib/copy_this/libs/rarinfo/archivereader.php index 7532a8f4a..75ae1ff9c 100644 --- a/lib/copy_this/www/lib/rarinfo/archivereader.php +++ b/lib/copy_this/libs/rarinfo/archivereader.php @@ -1,12 +1,11 @@ > 5) & 0x3f; - $hrs = ($dostime >> 11) & 0x1f; - $day = ($dostime >> 16) & 0x1f; - $mon = ($dostime >> 21) & 0x0f; + $sec = 2 * ($dostime & 0x1f); + $min = ($dostime >> 5) & 0x3f; + $hrs = ($dostime >> 11) & 0x1f; + $day = ($dostime >> 16) & 0x1f; + $mon = ($dostime >> 21) & 0x0f; $year = (($dostime >> 25) & 0x7f) + 1980; return mktime($hrs, $min, $sec, $mon, $day, $year); @@ -81,24 +77,22 @@ abstract class ArchiveReader /** * Converts Windows FILETIME format timestamps to UNIX timestamps. * - * @param integer $low the low 32 bits - * @param integer $high the high 32 bits - * + * @param integer $low the low 32 bits + * @param integer $high the high 32 bits * @return integer UNIX timestamp */ public static function win2unixtime($low, $high) { $ushift = 116444736000000000; - $ftime = self::int64($low, $high); + $ftime = self::int64($low, $high); - return (int)floor(($ftime - $ushift) / 10000000); + return (int) floor(($ftime - $ushift) / 10000000); } /** * Converts a numeric value passed by reference to a hexadecimal string. * - * @param mixed $value the numeric value to convert - * + * @param mixed $value the numeric value to convert * @return void */ public static function convert2hex(&$value) @@ -114,8 +108,7 @@ abstract class ArchiveReader * This is fiddly on 32-bit systems for sizes larger than 2GB due to internal * limitations - filesize() returns a signed long - and so needs hackery. * - * @param string $file full path to the file - * + * @param string $file full path to the file * @return integer|float the file size in bytes */ public static function getFileSize($file) @@ -126,51 +119,44 @@ abstract class ArchiveReader // Hack for Windows if (DIRECTORY_SEPARATOR === '\\') { - if (!extension_loaded('com_dotnet')) { - return trim(shell_exec('for %f in (' . escapeshellarg($file) . ') do @echo %~zf')) + 0; + if (! extension_loaded('com_dotnet')) { + return trim(shell_exec('for %f in ('.escapeshellarg($file).') do @echo %~zf')) + 0; } $com = new COM('Scripting.FileSystemObject'); $f = $com->GetFile($file); - return $f->Size + 0; } // Hack for *nix $os = php_uname(); if (stripos($os, 'Darwin') !== false) { - $command = 'stat -f %z ' . escapeshellarg($file); + $command = 'stat -f %z '.escapeshellarg($file); } elseif (stripos($os, 'DiskStation') !== false) { - $command = 'ls -l ' . escapeshellarg($file) . ' | awk \'{print $5}\''; + $command = 'ls -l '.escapeshellarg($file).' | awk \'{print $5}\''; } else { - $command = 'stat -c %s ' . escapeshellarg($file); + $command = 'stat -c %s '.escapeshellarg($file); } - return trim(shell_exec($command)) + 0; } /** * Returns human-readable byte sizes as formatted strings. * - * @param integer $bytes the size to format - * @param integer $round decimal places limit - * + * @param integer $bytes the size to format + * @param integer $round decimal places limit * @return string human-readable size */ - public static function formatSize($bytes, $round = 1) + public static function formatSize($bytes, $round=1) { $suffix = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'); - for ($i = 0; $bytes > 1024 && isset($suffix[$i + 1]); $i++) { - $bytes /= 1024; - } - - return round($bytes, $round) . ' ' . $suffix[$i]; + for ($i = 0; $bytes > 1024 && isset($suffix[$i+1]); $i++) {$bytes /= 1024;} + return round($bytes, $round).' '.$suffix[$i]; } /** * Creates a directory if it doesn't already exist. * - * @param string $dir the directory path - * + * @param string $dir the directory path * @return boolean false if the directory already exists */ public static function makeDirectory($dir) @@ -178,7 +164,7 @@ abstract class ArchiveReader if (file_exists($dir)) return false; - mkdir($dir, 0777, true); + mkdir($dir, 0777, TRUE); chmod($dir, 0777); return true; @@ -189,19 +175,18 @@ abstract class ArchiveReader * With an array of needles, the result will be a sorted list with the positions * as keys and a list of all matching needle keys as the values. * - * @param string $haystack the string to search - * @param string|array $needle the string or list of strings to find - * + * @param string $haystack the string to search + * @param string|array $needle the string or list of strings to find * @return array|boolean the needle positions, or false if none found */ - public static function strposall($haystack, $needle, $offset = 0) + public static function strposall($haystack, $needle, $offset=0) { - $start = $offset; - $hlen = strlen($haystack); + $start = $offset; + $hlen = strlen($haystack); $isArray = is_array($needle); $results = array(); - foreach ((array)$needle as $key => $value) { + foreach ((array) $needle as $key => $value) { if (($vlen = strlen($value)) == 0) continue; while ($offset < $hlen && ($pos = strpos($haystack, $value, $offset)) !== false) { @@ -216,7 +201,6 @@ abstract class ArchiveReader } if (!empty($results)) { ksort($results); - return $isArray ? $results : array_values($results); } @@ -227,14 +211,12 @@ abstract class ArchiveReader /** * The last error message. - * * @var string */ public $error = ''; /** * The number of files in the archive file/data. - * * @var integer */ public $fileCount = 0; @@ -242,13 +224,12 @@ abstract class ArchiveReader /** * Default constructor for loading and analyzing archive files. * - * @param string $file path to the archive file - * @param boolean $isFragment true if file is an archive fragment - * @param array $range the start and end byte positions - * + * @param string $file path to the archive file + * @param boolean $isFragment true if file is an archive fragment + * @param array $range the start and end byte positions * @return void */ - public function __construct($file = null, $isFragment = false, array $range = null) + public function __construct($file=null, $isFragment=false, array $range=null) { if ($file) $this->open($file, $isFragment, $range); } @@ -257,34 +238,26 @@ abstract class ArchiveReader * Opens a handle to the archive file and analyzes the archive contents, * optionally within a defined byte range only. * - * @param string $file path to the file - * @param boolean $isFragment true if file is an archive fragment - * @param array $range the start and end byte positions - * + * @param string $file path to the file + * @param boolean $isFragment true if file is an archive fragment + * @param array $range the start and end byte positions * @return boolean false if archive analysis fails */ - public function open($file, $isFragment = false, array $range = null) + public function open($file, $isFragment=false, array $range=null) { $this->reset(); $this->isFragment = $isFragment; - if (!$this->setRange($range)) { - return false; - } + if (!$this->setRange($range)) {return false;} if (!$file || !($archive = realpath($file)) || !is_file($archive)) { $this->error = "File does not exist ($file)"; - return false; } $this->file = $archive; $this->fileSize = self::getFileSize($archive); - if (!$this->end) { - $this->end = $this->fileSize - 1; - } - if (!$this->checkRange()) { - return false; - } + if (!$this->end) {$this->end = $this->fileSize - 1;} + if (!$this->checkRange()) {return false;} // Open the file handle $this->handle = fopen($archive, 'rb'); @@ -299,39 +272,30 @@ abstract class ArchiveReader * * This method is recommended when dealing with file fragments. * - * @param string $data archive data to be analyzed - * @param boolean $isFragment true if data is an archive fragment - * @param array $range the start and end byte positions - * + * @param string $data archive data to be analyzed + * @param boolean $isFragment true if data is an archive fragment + * @param array $range the start and end byte positions * @return boolean false if archive analysis fails */ - public function setData($data, $isFragment = false, array $range = null) + public function setData($data, $isFragment=false, array $range=null) { $this->reset(); $this->isFragment = $isFragment; - if (!$this->setRange($range)) { - return false; - } + if (!$this->setRange($range)) {return false;} if (($dsize = strlen($data)) == 0) { $this->error = 'No data was passed, nothing to analyze'; - return false; } // Store the data locally up to max bytes $data = ($dsize > $this->maxReadBytes) ? substr($data, 0, $this->maxReadBytes) : $data; $this->dataSize = strlen($data); - if (!$this->end) { - $this->end = $this->dataSize - 1; - } - if (!$this->checkRange()) { - return false; - } + if (!$this->end) {$this->end = $this->dataSize - 1;} + if (!$this->checkRange()) {return false;} $this->data = $data; $this->rewind(); - return $this->analyze(); } @@ -352,8 +316,7 @@ abstract class ArchiveReader /** * Sets the maximum number of stored data bytes to analyze. * - * @param integer $bytes the max bytes to read - * + * @param integer $bytes the max bytes to read * @return void */ public function setMaxReadBytes($bytes) @@ -377,8 +340,7 @@ abstract class ArchiveReader /** * Magic method for accessing protected properties. * - * @param string $name the property name - * + * @param string $name the property name * @return mixed the property value * @throws RuntimeException * @throws LogicException @@ -386,14 +348,12 @@ abstract class ArchiveReader public function __get($name) { // For backwards compatibility - if ($name == 'file') { - return $this->file; - } + if ($name == 'file') {return $this->file;} if (!isset($this->$name)) - throw new RuntimeException('Undefined property: ' . get_class($this) . '::$' . $name); + throw new RuntimeException('Undefined property: '.get_class($this).'::$'.$name); - throw new LogicException('Cannot access protected property ' . get_class($this) . '::$' . $name); + throw new LogicException('Cannot access protected property '.get_class($this).'::$'.$name); } /** @@ -410,11 +370,10 @@ abstract class ArchiveReader * Convenience method that outputs a summary list of the archive information, * useful for pretty-printing. * - * @param boolean $full return a full summary? - * + * @param boolean $full return a full summary? * @return array archive summary */ - abstract public function getSummary($full = false); + abstract public function getSummary($full=false); /** * Parses the stored archive info and returns a list of records for each of the @@ -440,98 +399,84 @@ abstract class ArchiveReader /** * Path to the archive file (if any). - * * @var string */ protected $file = ''; /** * File handle for the current archive. - * * @var resource */ protected $handle; /** * The maximum number of stored data bytes to analyze. - * * @var integer */ protected $maxReadBytes = 1048576; /** * The maximum length of filenames (for sanity checking). - * * @var integer */ protected $maxFilenameLength = 256; /** * Is this a file/data fragment? - * * @var boolean */ protected $isFragment = false; /** * The stored archive file data. - * * @var string */ protected $data = ''; /** * The size in bytes of the currently stored data. - * * @var integer */ protected $dataSize = 0; /** * The size in bytes of the archive file. - * * @var integer */ protected $fileSize = 0; /** * The starting position for the analysis. - * * @var integer */ protected $start = 0; /** * The ending position for the analysis. - * * @var integer */ protected $end = 0; /** * The number of bytes to analyze from the $start position. - * * @var integer */ protected $length = 0; /** * The current position relative to the $start position. - * * @var integer */ protected $offset = 0; /** * The position of the marker/signature relative to the $start position. - * * @var integer */ protected $markerPosition; /** * The list of any temporary files created by the reader. - * * @var array */ protected $tempFiles = array(); @@ -540,23 +485,20 @@ abstract class ArchiveReader * Sets the absolute start and end positions in the file/data to be analyzed * (zero-indexed and inclusive of the end byte). * - * @param array $range the start and end byte positions - * + * @param array $range the start and end byte positions * @return boolean false if ranges are invalid */ - protected function setRange(array $range = null) + protected function setRange(array $range=null) { - $start = isset($range[0]) ? (int)$range[0] : 0; - $end = isset($range[1]) ? (int)$range[1] : 0; + $start = isset($range[0]) ? (int) $range[0] : 0; + $end = isset($range[1]) ? (int) $range[1] : 0; if ($start != $range[0] || $end != $range[1] || $start < 0 || $end < 0) { $this->error = "Start ($start) and end ($end) points must be positive integers"; - return false; } if ($end < $start) { $this->error = "End point ($end) must be higher than start point ($start)"; - return false; } $this->start = $start; @@ -577,7 +519,6 @@ abstract class ArchiveReader $mlen = $this->file ? $this->fileSize : $this->dataSize; if ($mlen && ($this->end >= $mlen || $this->start >= $mlen || $this->length < 1)) { $this->error = "Byte range ({$this->start}-{$this->end}) is invalid"; - return false; } $this->error = ''; @@ -588,8 +529,7 @@ abstract class ArchiveReader /** * Returns data within the given absolute byte range of the current file/data. * - * @param array $range the absolute start and end positions - * + * @param array $range the absolute start and end positions * @return string|boolean the requested data or false on error */ protected function getRange(array $range) @@ -598,7 +538,6 @@ abstract class ArchiveReader $original = array($this->start, $this->end, $this->length); if (!$this->setRange($range)) { list($this->start, $this->end, $this->length) = $original; - return false; } @@ -616,9 +555,8 @@ abstract class ArchiveReader * Saves data within the given absolute byte range of the current file/data to * the destination file. * - * @param array $range the absolute start and end positions - * @param string $destination full path of the file to create - * + * @param array $range the absolute start and end positions + * @param string $destination full path of the file to create * @return integer|boolean number of bytes written or false on error */ protected function saveRange(array $range, $destination) @@ -627,7 +565,6 @@ abstract class ArchiveReader $original = array($this->start, $this->end, $this->length); if (!$this->setRange($range)) { list($this->start, $this->end, $this->length) = $original; - return false; } @@ -653,8 +590,7 @@ abstract class ArchiveReader * Reads the given number of bytes from the archive file/data and moves the * offset pointer forward. * - * @param integer $num number of bytes to read - * + * @param integer $num number of bytes to read * @return string the byte string * @throws InvalidArgumentException * @throws RangeException @@ -696,8 +632,7 @@ abstract class ArchiveReader * impossible or needs an incredibly slow hack due to the fseek() pointer not * behaving after 2GB. The only real solution here is to use a 64-bit system. * - * @param integer $pos new pointer position - * + * @param integer $pos new pointer position * @return void * @throws RuntimeException * @throws InvalidArgumentException @@ -711,7 +646,7 @@ abstract class ArchiveReader $max = PHP_INT_MAX; $file_pos = $this->start + $pos; if ($file_pos >= $max) { - $this->error = 'The file is too large for this PHP version (> ' . self::formatSize($max) . ')'; + $this->error = 'The file is too large for this PHP version (> '.self::formatSize($max).')'; throw new RuntimeException($this->error); } fseek($this->handle, $file_pos, SEEK_SET); @@ -769,14 +704,13 @@ abstract class ArchiveReader * Calculates a temporary file name based on hashes of the given data string * or the stored data. * - * @param string $data the source data to be hashed - * + * @param string $data the source data to be hashed * @return array the hash and temporary file path values */ - protected function getTempFileName($data = null) + protected function getTempFileName($data=null) { - $hash = $data ? md5($data) : md5(substr($this->data, 0, 16 * 1024)); - $path = $this->getTempDirectory() . DIRECTORY_SEPARATOR . $hash . '.tmp'; + $hash = $data ? md5($data) : md5(substr($this->data, 0, 16*1024)); + $path = $this->getTempDirectory().DIRECTORY_SEPARATOR.$hash.'.tmp'; return array($hash, $path); } @@ -789,7 +723,7 @@ abstract class ArchiveReader */ protected function getTempDirectory() { - $dir = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'archivereader'; + $dir = sys_get_temp_dir().DIRECTORY_SEPARATOR.'archivereader'; self::makeDirectory($dir); return $dir; @@ -832,4 +766,4 @@ abstract class ArchiveReader clearstatcache(); } -} // End ArchiveReader class \ No newline at end of file +} // End ArchiveReader class diff --git a/lib/copy_this/libs/rarinfo/par2info.php b/lib/copy_this/libs/rarinfo/par2info.php new file mode 100644 index 000000000..05866d1c4 --- /dev/null +++ b/lib/copy_this/libs/rarinfo/par2info.php @@ -0,0 +1,454 @@ + + * + * // Load the PAR2 file or data + * $par2 = new Par2Info; + * $par2->open('./foo.par2'); // or $par2->setData($data); + * if ($par2->error) { + * echo "Error: {$par2->error}\n"; + * exit; + * } + * + * // Process the recovery set file list & hashes + * $files = $par2->getFileList(); + * foreach ($files as $fileID => $file) { + * echo "Input file: {$file['name']} ({$file['size']}):\n"; + * echo "-- MD5 hash: {$file['hash']}:\n"; + * echo "-- MD5 hash (16KB): {$file['hash_16K']}:\n"; + * } + * } + * + * + * + * @link http://parchive.sourceforge.net/docs/specifications/parity-volume-spec/article-spec.html + * + * @author Hecks + * @copyright (c) 2010-2013 Hecks + * @license Modified BSD + * @version 1.7 + */ +class Par2Info extends ArchiveReader +{ + // ------ Class constants ----------------------------------------------------- + + /**#@+ + * PAR2 file format values + */ + + // Packet Marker + const PACKET_MARKER = "PAR2\x00PKT"; + + // Core packet types + const PACKET_MAIN = "PAR 2.0\x00Main\x00\x00\x00\x00"; + const PACKET_FILEDESC = "PAR 2.0\x00FileDesc"; + const PACKET_FILEVER = "PAR 2.0\x00IFSC\x00\x00\x00\x00"; + const PACKET_RECOVERY = "PAR 2.0\x00RecvSlic"; + const PACKET_CREATOR = "PAR 2.0\x00Creator\x00"; + + // Optional packet types + const PACKET_FILENAME_UC = "PAR 2.0\x00UniFileN"; + const PACKET_COMMENT_ASCII = "PAR 2.0\x00CommASCI"; + const PACKET_COMMENT_UC = "PAR 2.0\x00CommUni\x00"; + const PACKET_INPUT_BLOCK = "PAR 2.0\x00FileSlic"; + const PACKET_RECOVERY_VER = "PAR 2.0\x00RFSC\x00\x00\x00\x00"; + const PACKET_PACKED_MAIN = "PAR 2.0\x00PkdMain\x00"; + const PACKET_PACKED_RECOVERY = "PAR 2.0\x00PkdRecvS"; + + /**#@-*/ + + /** + * Format for unpacking each PAR2 packet header, in standard and Perl-compatible + * (PHP >= 5.5.0) versions. + */ + const FORMAT_PACKET_HEADER = 'A8head_marker/Vhead_length/Vhead_length_high/H32head_hash/H32head_set_id/A16head_type'; + const PL_FORMAT_PACKET_HEADER = 'a8head_marker/Vhead_length/Vhead_length_high/H32head_hash/H32head_set_id/a16head_type'; + + /** + * Format for unpacking the body of a Main packet. + */ + const FORMAT_PACKET_MAIN = 'Vblock_size/Vblock_size_high/Vrec_file_count'; + + /** + * Format for unpacking the body of a File Description packet. + */ + const FORMAT_PACKET_FILEDESC = 'H32file_id/H32file_hash/H32file_hash_16K/Vfile_length/Vfile_length_high'; + + + // ------ Instance variables and methods --------------------------------------- + + /** + * List of packet names corresponding to packet types. + * @var array + */ + protected $packetNames = array( + self::PACKET_MAIN => 'Main', + self::PACKET_FILEDESC => 'File Description', + self::PACKET_FILEVER => 'File Block Verification', + self::PACKET_RECOVERY => 'Recovery Block', + self::PACKET_CREATOR => 'Creator', + // Optional + self::PACKET_FILENAME_UC => 'Unicode Filename', + self::PACKET_COMMENT_ASCII => 'Comment ASCII', + self::PACKET_COMMENT_UC => 'Comment Unicode', + self::PACKET_INPUT_BLOCK => 'Input File Block', + self::PACKET_RECOVERY_VER => 'Recovery File Block Verification', + self::PACKET_PACKED_MAIN => 'Packed Main', + self::PACKET_PACKED_RECOVERY => 'Packed Recovery', + ); + + /** + * Number of valid recovery blocks in the file/data. + * @var integer + */ + public $blockCount = 0; + + /** + * Size in bytes of the recovery blocks. + * @var integer + */ + public $blockSize = 0; + + /** + * Details of the client that created the PAR2 file/data. + * @var string + */ + public $client = ''; + + /** + * Convenience method that outputs a summary list of the file/data information, + * useful for pretty-printing. + * + * @param boolean $full add file list to output? + * @return array file/data summary + */ + public function getSummary($full=false) + { + $summary = array( + 'file_name' => $this->file, + 'file_size' => $this->fileSize, + 'data_size' => $this->dataSize, + 'client' => $this->client, + 'block_count' => $this->blockCount, + 'block_size' => $this->blockSize, + 'file_count' => $this->fileCount, + ); + if ($full) { + $summary['file_list'] = $this->getFileList(); + } + if ($this->error) { + $summary['error'] = $this->error; + } + + return $summary; + } + + /** + * Returns a list of the PAR2 packets found in the file/data in human-readable + * format (for debugging purposes only). + * + * @param boolean $full include all packet details in output? + * @return array|boolean list of packets, or false if none available + */ + public function getPackets($full=false) + { + // Check that packets are stored + if (empty($this->packets)) {return false;} + + // Build the packet list + $ret = array(); + + foreach ($this->packets AS $packet) { + + // File Block Verification packets are very verbose + if (!$full && $packet['head_type'] == self::PACKET_FILEVER) {continue;} + + $p = array(); + $p['type_name'] = isset($this->packetNames[$packet['head_type']]) ? $this->packetNames[$packet['head_type']] : 'Unknown'; + $p += $packet; + + // Sanity check filename length + if (isset($p['file_name'])) {$p['file_name'] = substr($p['file_name'], 0, $this->maxFilenameLength);} + $ret[] = $p; + } + + return $ret; + } + + /** + * Parses the stored packets and returns a list of records for each of the + * files in the recovery set. + * + * @return array list of file records, empty if none are available + */ + public function getFileList() + { + $ret = array(); + foreach ($this->packets as $packet) { + if ($packet['head_type'] == self::PACKET_FILEDESC && !isset($ret[$packet['file_id']])) { + $ret[$packet['file_id']] = $this->getFilePacketSummary($packet); + } + if ($packet['head_type'] == self::PACKET_FILEVER && empty($ret[$packet['file_id']]['blocks'])) { + $ret[$packet['file_id']]['blocks'] = count($packet['block_checksums']); + } + } + + return $ret; + } + + /** + * List of File IDs found in the file/data. + * @var array + */ + protected $fileIDs = array(); + + /** + * List of packets found in the file/data. + * @var array + */ + protected $packets = array(); + + /** + * Returns a processed summary of a PAR2 File Description packet. + * + * @param array $packet a valid File Description packet + * @return array summary information + */ + protected function getFilePacketSummary($packet) + { + return array( + 'name' => !empty($packet['file_name']) ? substr($packet['file_name'], 0, $this->maxFilenameLength) : 'Unknown', + 'size' => isset($packet['file_length']) ? $packet['file_length'] : 0, + 'hash' => $packet['file_hash'], + 'hash_16K' => $packet['file_hash_16K'], + 'blocks' => 0, + 'next_offset' => $packet['next_offset'], + ); + } + + /** + * Returns the position of the first PAR2 Packet Marker string in the file/data. + * + * @return mixed Marker position, or false if none found + */ + public function findMarker() + { + if ($this->markerPosition !== null) + return $this->markerPosition; + + try { + $buff = $this->read(min($this->length, $this->maxReadBytes)); + $this->rewind(); + return $this->markerPosition = strpos($buff, self::PACKET_MARKER); + } catch (Exception $e) { + return false; + } + } + + /** + * Parses the PAR2 data and stores a list of valid packets locally. + * + * @return boolean false if parsing fails + */ + protected function analyze() + { + // Find the first Packet Marker, if there is one + if (($startPos = $this->findMarker()) === false) { + $this->error = 'Could not find a Packet Marker, not a valid PAR2 file'; + return false; + } + $this->seek($startPos); + + // Analyze all packets + while ($this->offset < $this->length) try { + + // Get the next packet header + $packet = $this->getNextPacket(); + + // Verify the packet + if ($this->verifyPacket($packet) === false) { + $this->error = "Packet failed checksum (offset: {$this->offset})"; + throw new Exception('Packet checksum failed'); + } + + // Process the current packet by type + $this->processPacket($packet); + + // Add the current packet to the list + $this->packets[] = $packet; + + // Skip to the next packet, if any + if ($this->offset != $packet['next_offset']) { + $this->seek($packet['next_offset']); + } + + // Sanity check + if ($packet['offset'] == $this->offset) { + $this->error = 'Parsing seems to be stuck'; + $this->close(); + return false; + } + + // No more readable data, or read error + } catch (Exception $e) { + if ($this->error) {$this->close(); return false;} + break; + } + + // Check for valid packets + if (empty($this->packets)) { + $this->error = 'No valid PAR2 packets were found'; + $this->close(); + return false; + } + + // Analysis was successful + $this->close(); + return true; + } + + /** + * Reads the start of the next packet header and returns the common packet + * info before further processing by packet type. + * + * @return array the next packet header info + */ + protected function getNextPacket() + { + // Start the packet info + $packet = array('offset' => $this->offset); + + // Unpack the packet header + $format = (version_compare(PHP_VERSION, '5.5.0') >= 0) + ? self::PL_FORMAT_PACKET_HEADER + : self::FORMAT_PACKET_HEADER; + $packet += self::unpack($format, $this->read(64)); + + // Convert packet size (64-bit integer) + $packet['head_length'] = self::int64($packet['head_length'], $packet['head_length_high']); + + // Add offset info for next packet (if any) + $packet['next_offset'] = $packet['offset'] + $packet['head_length']; + + // Return the packet info + return $packet; + } + + /** + * Verifies that the given packet is valid and parsable. + * + * @param array $packet the packet to verify + * @return boolean false on failure + */ + protected function verifyPacket($packet) + { + $offset = $this->offset; + + // Check the MD5 hash of the data from head_set_id to packet end + $this->seek($packet['offset'] + 32); + $data = $this->read($packet['head_length'] - 32); + $this->seek($offset); + + return (md5($data) === $packet['head_hash']); + } + + /** + * Processes a packet passed by reference and unpacks its body. + * + * @param array $packet the packet to process + * @return void + */ + protected function processPacket(&$packet) + { + // Packet type: MAIN + if ($packet['head_type'] == self::PACKET_MAIN) { + $packet += self::unpack(self::FORMAT_PACKET_MAIN, $this->read(12)); + $packet['block_size'] = self::int64($packet['block_size'], $packet['block_size_high']); + $this->blockSize = $packet['block_size']; + + // Unpack the File IDs of all files in the recovery set + $recoverable = array(); + for ($i = 0; $i < $packet['rec_file_count']; $i++) { + $recoverable = array_merge($recoverable, self::unpack('H32', $this->read(16))); + } + $packet['rec_file_ids'] = $recoverable; + + // Unpack any File IDs of files not in the recovery set + $unrecoverable = array(); + while ($this->offset < $packet['next_offset']) { + $unrecoverable = array_merge($unrecoverable, self::unpack('H32', $this->read(16))); + } + if (!empty($unrecoverable)) { + $packet['other_file_ids'] = $unrecoverable; + } + } + + // Packet type: FILE DESCRIPTION + elseif ($packet['head_type'] == self::PACKET_FILEDESC) { + $packet += self::unpack(self::FORMAT_PACKET_FILEDESC, $this->read(56)); + $packet['file_length'] = self::int64($packet['file_length'], $packet['file_length_high']); + $len = ($packet['offset'] + $packet['head_length']) - $this->offset; + $packet['file_name'] = rtrim($this->read($len)); + + // Add ID to the stored file list so we don't double-count + if (!isset($this->fileIDs[$packet['file_id']])) { + $this->fileIDs[$packet['file_id']] = true; + $this->fileCount++; + } + } + + // Packet type: FILE BLOCK VERIFICATION + elseif ($packet['head_type'] == self::PACKET_FILEVER) { + $packet += self::unpack('H32file_id', $this->read(16)); + + // Unpack the MD5/CRC32 checksum pairs + $packet['block_checksums'] = array(); + while ($this->offset < $packet['next_offset']) { + $packet['block_checksums'][] = self::unpack('H32md5/Vcrc32', $this->read(20)); + } + } + + // Packet type: RECOVERY BLOCK + elseif ($packet['head_type'] == self::PACKET_RECOVERY) { + $packet += self::unpack('Vexponent', $this->read(4)); + $this->blockCount++; + } + + // Packet type: CREATOR + elseif ($packet['head_type'] == self::PACKET_CREATOR) { + $len = ($packet['offset'] + $packet['head_length']) - $this->offset; + $packet['client'] = $this->read($len); + $this->client = rtrim($packet['client']); + } + } + + /** + * Resets the instance variables before parsing new data. + * + * @return void + */ + protected function reset() + { + parent::reset(); + + $this->client = ''; + $this->blockCount = 0; + $this->blockSize = 0; + $this->fileIDs = array(); + $this->packets = array(); + } + +} // End Par2Info class diff --git a/lib/copy_this/libs/rarinfo/pipereader.php b/lib/copy_this/libs/rarinfo/pipereader.php new file mode 100644 index 000000000..81aed3627 --- /dev/null +++ b/lib/copy_this/libs/rarinfo/pipereader.php @@ -0,0 +1,246 @@ + errors.txt' to the command) or by combining with STDOUT ('2>&1'). + * Then the application must either read the file or parse the output for errors. + * + * @author Hecks + * @copyright (c) 2010-2013 Hecks + * @license Modified BSD + * @version 1.2 + */ +class PipeReader +{ + /** + * The last error message. + * @var string + */ + public $error = ''; + + /** + * The last process exit code. + * @var integer + */ + public $exitCode = 0; + + /** + * Default constructor for opening a pipe. + * + * @param string $command the command to execute + * @return void + */ + public function __construct($command=null) + { + if ($command) $this->open($command); + } + + /** + * Opens a pipe to stream the output of a given command. + * + * Note that it's the responsibility of the calling application to sanitize + * the command with e.g. escapeshellcmd(), escapeshellarg(), etc. + * + * @param string $command the command to execute + * @return boolean false if the pipe could not be openend + */ + public function open($command) + { + $this->reset(); + + if (!($handle = popen($command, 'rb'))) { + $this->error = "Could not execute command: ($command)"; + return false; + } + + $this->handle = $handle; + $this->command = $command; + + return true; + } + + /** + * Closes any open pipe handle and sets the exit code. + * + * @return void + */ + public function close() + { + if (is_resource($this->handle)) { + $this->exitCode = pclose($this->handle); + } + $this->handle = null; + } + + /** + * Reads the given number of bytes from the piped command output and moves the + * offset pointer forward, with optional confirmation that the requested bytes + * are available. + * + * @param integer $num number of bytes to read + * @param booleann $confirm check available bytes? + * @return string the byte string + * @throws InvalidArgumentException + */ + public function read($num, $confirm=true) + { + if ($num < 1) { + throw new InvalidArgumentException("Could not read {$num} bytes from offset {$this->offset}"); + } elseif ($num == 0) { + return ''; + } + + // Read the requested bytes + if ($this->command && is_resource($this->handle)) { + $read = ''; $rlen = $num; + while ($rlen > 0 && !feof($this->handle)) { + $data = fread($this->handle, min($this->maxReadBytes, $rlen)); + $rlen -= strlen($data); + $read .= $data; + } + } + + // Confirm the read length? + if ($confirm && (!isset($read) || strlen($read) < $num)) { + $this->offset = $this->tell(); + throw new InvalidArgumentException("Could not read {$num} bytes from offset {$this->offset}"); + } + + // Move the data pointer + $this->offset = $this->tell(); + + return isset($read) ? $read : ''; + } + + /** + * Convenience method for reading the remaining bytes from the piped output. + * + * @return string the remaining output data + */ + public function readAll() + { + $data = ''; + while ($read = $this->read($this->maxReadBytes, false)) { + $data .= $read; + } + + return $data; + } + + /** + * Convenience method for reading a single line, with the line ending included + * in the output. + * + * @return string|boolean the next output line, or false if none available + */ + public function readLine() + { + if (!$this->command || !is_resource($this->handle) || feof($this->handle)) + return false; + + $line = fgets($this->handle, $this->maxReadBytes); + $this->offset = $this->tell(); + + return $line; + } + + /** + * Moves the current offset pointer to a position in the piped command output. + * + * Since only seeking ahead in the pipe is possible - and only by reading the + * output stream - seeking to an earlier offset necessarily means invoking the + * command again, so care must be taken that any commands are idempotent. + * + * @param integer $pos new pointer position + * @return void + * @throws InvalidArgumentException + */ + public function seek($pos) + { + if ($pos < 0) + throw new InvalidArgumentException("Could not seek to offset: {$pos}"); + + if ($this->command) { + if ($pos < $this->offset) { + $this->open($this->command); + } + if ($pos > $this->offset && $pos > 0) { + $this->read($pos - $this->offset); + } + } + + $this->offset = $this->tell(); + } + + /** + * Provides the absolute position within the current piped output. + * + * @return integer the absolute position + */ + public function tell() + { + if ($this->command && is_resource($this->handle)) + return ftell($this->handle); + + return $this->offset; + } + + /** + * Sets the maximum number of bytes to read in one operation. + * + * @param integer $bytes the max bytes to read + * @return void + */ + public function setMaxReadBytes($bytes) + { + if (is_int($bytes) && $bytes > 0) { + $this->maxReadBytes = $bytes; + } + } + + /** + * The command string to be executed for piped output. + * @var string + */ + protected $command = ''; + + /** + * Stream handle for the current pipe. + * @var resource + */ + protected $handle; + + /** + * The maximum number of bytes to read in one operation. + * @var integer + */ + protected $maxReadBytes = 1048576; + + /** + * The current position in the piped output. + * @var integer + */ + protected $offset = 0; + + /** + * Resets the instance variables. + * + * @return void + */ + protected function reset() + { + $this->close(); + $this->error = ''; + $this->exitCode = 0; + $this->command = ''; + $this->offset = 0; + } + +} // End PipeReader class diff --git a/lib/copy_this/www/lib/rarinfo/rarinfo.php b/lib/copy_this/libs/rarinfo/rarinfo.php similarity index 72% rename from lib/copy_this/www/lib/rarinfo/rarinfo.php rename to lib/copy_this/libs/rarinfo/rarinfo.php index e66a75613..83f6e2c13 100644 --- a/lib/copy_this/www/lib/rarinfo/rarinfo.php +++ b/lib/copy_this/libs/rarinfo/rarinfo.php @@ -47,10 +47,10 @@ require_once dirname(__FILE__) . '/pipereader.php'; * TRUE as the second parameter for the open() or setData() methods to skip the * error messages and allow a forced search for valid File Header blocks. * - * @author Hecks + * @author Hecks * @copyright (c) 2010-2014 Hecks - * @license Modified BSD - * @version 5.6 + * @license Modified BSD + * @version 5.6 */ class RarInfo extends ArchiveReader { @@ -61,87 +61,87 @@ class RarInfo extends ArchiveReader */ // Block types - const BLOCK_MARK = 0x72; - const BLOCK_MAIN = 0x73; - const BLOCK_FILE = 0x74; - const BLOCK_OLD_COMMENT = 0x75; - const BLOCK_OLD_EXTRA = 0x76; - const BLOCK_OLD_SUB = 0x77; - const BLOCK_OLD_RECOVERY = 0x78; - const BLOCK_OLD_AUTH = 0x79; - const BLOCK_SUB = 0x7a; - const BLOCK_ENDARC = 0x7b; - const BLOCK_NULL = 0x00; + const BLOCK_MARK = 0x72; + const BLOCK_MAIN = 0x73; + const BLOCK_FILE = 0x74; + const BLOCK_OLD_COMMENT = 0x75; + const BLOCK_OLD_EXTRA = 0x76; + const BLOCK_OLD_SUB = 0x77; + const BLOCK_OLD_RECOVERY = 0x78; + const BLOCK_OLD_AUTH = 0x79; + const BLOCK_SUB = 0x7a; + const BLOCK_ENDARC = 0x7b; + const BLOCK_NULL = 0x00; // Flags for BLOCK_MAIN - const MAIN_VOLUME = 0x0001; - const MAIN_COMMENT = 0x0002; - const MAIN_LOCK = 0x0004; - const MAIN_SOLID = 0x0008; - const MAIN_NEWNUMBERING = 0x0010; - const MAIN_AUTH = 0x0020; - const MAIN_RECOVERY = 0x0040; - const MAIN_PASSWORD = 0x0080; - const MAIN_FIRSTVOLUME = 0x0100; - const MAIN_ENCRYPTVER = 0x0200; + const MAIN_VOLUME = 0x0001; + const MAIN_COMMENT = 0x0002; + const MAIN_LOCK = 0x0004; + const MAIN_SOLID = 0x0008; + const MAIN_NEWNUMBERING = 0x0010; + const MAIN_AUTH = 0x0020; + const MAIN_RECOVERY = 0x0040; + const MAIN_PASSWORD = 0x0080; + const MAIN_FIRSTVOLUME = 0x0100; + const MAIN_ENCRYPTVER = 0x0200; // Flags for BLOCK_FILE - const FILE_SPLIT_BEFORE = 0x0001; - const FILE_SPLIT_AFTER = 0x0002; - const FILE_PASSWORD = 0x0004; - const FILE_COMMENT = 0x0008; - const FILE_SOLID = 0x0010; - const FILE_DICTMASK = 0x00e0; - const FILE_DICT64 = 0x0000; - const FILE_DICT128 = 0x0020; - const FILE_DICT256 = 0x0040; - const FILE_DICT512 = 0x0060; - const FILE_DICT1024 = 0x0080; - const FILE_DICT2048 = 0x00a0; - const FILE_DICT4096 = 0x00c0; - const FILE_DIRECTORY = 0x00e0; - const FILE_LARGE = 0x0100; - const FILE_UNICODE = 0x0200; - const FILE_SALT = 0x0400; - const FILE_VERSION = 0x0800; - const FILE_EXTTIME = 0x1000; - const FILE_EXTFLAGS = 0x2000; + const FILE_SPLIT_BEFORE = 0x0001; + const FILE_SPLIT_AFTER = 0x0002; + const FILE_PASSWORD = 0x0004; + const FILE_COMMENT = 0x0008; + const FILE_SOLID = 0x0010; + const FILE_DICTMASK = 0x00e0; + const FILE_DICT64 = 0x0000; + const FILE_DICT128 = 0x0020; + const FILE_DICT256 = 0x0040; + const FILE_DICT512 = 0x0060; + const FILE_DICT1024 = 0x0080; + const FILE_DICT2048 = 0x00a0; + const FILE_DICT4096 = 0x00c0; + const FILE_DIRECTORY = 0x00e0; + const FILE_LARGE = 0x0100; + const FILE_UNICODE = 0x0200; + const FILE_SALT = 0x0400; + const FILE_VERSION = 0x0800; + const FILE_EXTTIME = 0x1000; + const FILE_EXTFLAGS = 0x2000; // Flags for BLOCK_ENDARC - const ENDARC_NEXT_VOLUME = 0x0001; - const ENDARC_DATACRC = 0x0002; - const ENDARC_REVSPACE = 0x0004; - const ENDARC_VOLNR = 0x0008; + const ENDARC_NEXT_VOLUME = 0x0001; + const ENDARC_DATACRC = 0x0002; + const ENDARC_REVSPACE = 0x0004; + const ENDARC_VOLNR = 0x0008; // Flags for all blocks - const SKIP_IF_UNKNOWN = 0x4000; - const LONG_BLOCK = 0x8000; + const SKIP_IF_UNKNOWN = 0x4000; + const LONG_BLOCK = 0x8000; // Subtypes for BLOCK_SUB - const SUBTYPE_COMMENT = 'CMT'; - const SUBTYPE_ACL = 'ACL'; - const SUBTYPE_STREAM = 'STM'; - const SUBTYPE_UOWNER = 'UOW'; - const SUBTYPE_AUTHVER = 'AV'; - const SUBTYPE_RECOVERY = 'RR'; - const SUBTYPE_OS2EA = 'EA2'; - const SUBTYPE_BEOSEA = 'EABE'; + const SUBTYPE_COMMENT = 'CMT'; + const SUBTYPE_ACL = 'ACL'; + const SUBTYPE_STREAM = 'STM'; + const SUBTYPE_UOWNER = 'UOW'; + const SUBTYPE_AUTHVER = 'AV'; + const SUBTYPE_RECOVERY = 'RR'; + const SUBTYPE_OS2EA = 'EA2'; + const SUBTYPE_BEOSEA = 'EABE'; // Compression methods - const METHOD_STORE = 0x30; - const METHOD_FASTEST = 0x31; - const METHOD_FAST = 0x32; - const METHOD_NORMAL = 0x33; - const METHOD_GOOD = 0x34; - const METHOD_BEST = 0x35; + const METHOD_STORE = 0x30; + const METHOD_FASTEST = 0x31; + const METHOD_FAST = 0x32; + const METHOD_NORMAL = 0x33; + const METHOD_GOOD = 0x34; + const METHOD_BEST = 0x35; // OS types const OS_MSDOS = 0; - const OS_OS2 = 1; + const OS_OS2 = 1; const OS_WIN32 = 2; - const OS_UNIX = 3; + const OS_UNIX = 3; const OS_MACOS = 4; - const OS_BEOS = 5; + const OS_BEOS = 5; /**#@-*/ @@ -172,77 +172,77 @@ class RarInfo extends ArchiveReader */ // Block types - const R50_BLOCK_MAIN = 0x01; - const R50_BLOCK_FILE = 0x02; - const R50_BLOCK_SERVICE = 0x03; - const R50_BLOCK_CRYPT = 0x04; - const R50_BLOCK_ENDARC = 0x05; + const R50_BLOCK_MAIN = 0x01; + const R50_BLOCK_FILE = 0x02; + const R50_BLOCK_SERVICE = 0x03; + const R50_BLOCK_CRYPT = 0x04; + const R50_BLOCK_ENDARC = 0x05; // Flags for all block types - const R50_HAS_EXTRA = 0x0001; - const R50_HAS_DATA = 0x0002; - const R50_SKIP_IF_UNKNOWN = 0x0004; - const R50_SPLIT_BEFORE = 0x0008; - const R50_SPLIT_AFTER = 0x0010; - const R50_IS_CHILD = 0x0020; - const R50_INHERITED = 0x0040; + const R50_HAS_EXTRA = 0x0001; + const R50_HAS_DATA = 0x0002; + const R50_SKIP_IF_UNKNOWN = 0x0004; + const R50_SPLIT_BEFORE = 0x0008; + const R50_SPLIT_AFTER = 0x0010; + const R50_IS_CHILD = 0x0020; + const R50_INHERITED = 0x0040; // Service block types - const R50_SERVICE_COMMENT = 'CMT'; - const R50_SERVICE_QUICKOPEN = 'QO'; - const R50_SERVICE_ACL = 'ACL'; - const R50_SERVICE_STREAM = 'STM'; - const R50_SERVICE_RECOVERY = 'RR'; + const R50_SERVICE_COMMENT = 'CMT'; + const R50_SERVICE_QUICKOPEN = 'QO'; + const R50_SERVICE_ACL = 'ACL'; + const R50_SERVICE_STREAM = 'STM'; + const R50_SERVICE_RECOVERY = 'RR'; // Flags for R50_BLOCK_MAIN - const R50_MAIN_VOLUME = 0x0001; - const R50_MAIN_VOLNUMBER = 0x0002; - const R50_MAIN_SOLID = 0x0004; - const R50_MAIN_RECOVERY = 0x0008; - const R50_MAIN_LOCK = 0x0010; + const R50_MAIN_VOLUME = 0x0001; + const R50_MAIN_VOLNUMBER = 0x0002; + const R50_MAIN_SOLID = 0x0004; + const R50_MAIN_RECOVERY = 0x0008; + const R50_MAIN_LOCK = 0x0010; // Flags for R50_BLOCK_FILE - const R50_FILE_DIRECTORY = 0x0001; - const R50_FILE_UTIME = 0x0002; - const R50_FILE_CRC32 = 0x0004; - const R50_FILE_UNPUNKNOWN = 0x0008; + const R50_FILE_DIRECTORY = 0x0001; + const R50_FILE_UTIME = 0x0002; + const R50_FILE_CRC32 = 0x0004; + const R50_FILE_UNPUNKNOWN = 0x0008; // Flags for R50_BLOCK_ENDARC const R50_ENDARC_NEXT_VOLUME = 0x0001; // Extra record types for R50_BLOCK_MAIN - const R50_MEXTRA_LOCATOR = 0x01; + const R50_MEXTRA_LOCATOR = 0x01; // Flags for R50_MEXTRA_LOCATOR - const R50_MEXTRA_LOC_QLIST = 0x0001; - const R50_MEXTRA_LOC_RR = 0x0002; + const R50_MEXTRA_LOC_QLIST = 0x0001; + const R50_MEXTRA_LOC_RR = 0x0002; // Extra record types for R50_BLOCK_FILE - const R50_FEXTRA_CRYPT = 0x01; - const R50_FEXTRA_HASH = 0x02; - const R50_FEXTRA_HTIME = 0x03; - const R50_FEXTRA_VERSION = 0x04; - const R50_FEXTRA_REDIR = 0x05; - const R50_FEXTRA_UOWNER = 0x06; - const R50_FEXTRA_SUBDATA = 0x07; + const R50_FEXTRA_CRYPT = 0x01; + const R50_FEXTRA_HASH = 0x02; + const R50_FEXTRA_HTIME = 0x03; + const R50_FEXTRA_VERSION = 0x04; + const R50_FEXTRA_REDIR = 0x05; + const R50_FEXTRA_UOWNER = 0x06; + const R50_FEXTRA_SUBDATA = 0x07; // Flags for R50_FEXTRA_HTIME - const R50_FEXTRA_HT_UNIX = 0x0001; - const R50_FEXTRA_HT_MTIME = 0x0002; - const R50_FEXTRA_HT_CTIME = 0x0004; - const R50_FEXTRA_HT_ATIME = 0x0008; + const R50_FEXTRA_HT_UNIX = 0x0001; + const R50_FEXTRA_HT_MTIME = 0x0002; + const R50_FEXTRA_HT_CTIME = 0x0004; + const R50_FEXTRA_HT_ATIME = 0x0008; // Compression methods - const R50_METHOD_STORE = 0; - const R50_METHOD_FASTEST = 1; - const R50_METHOD_FAST = 2; - const R50_METHOD_NORMAL = 3; - const R50_METHOD_GOOD = 4; - const R50_METHOD_BEST = 5; + const R50_METHOD_STORE = 0; + const R50_METHOD_FASTEST = 1; + const R50_METHOD_FAST = 2; + const R50_METHOD_NORMAL = 3; + const R50_METHOD_GOOD = 4; + const R50_METHOD_BEST = 5; // OS types const R50_OS_WIN32 = 0; - const R50_OS_UNIX = 1; + const R50_OS_UNIX = 1; /**#@-*/ @@ -250,111 +250,100 @@ class RarInfo extends ArchiveReader /** * Signature for the RAR Marker block. - * * @var string */ protected $markerBlock = "\x52\x61\x72\x21\x1a\x07\x00"; /** * Signature for RAR 5.0 format archives. - * * @var string */ protected $markerRar50 = "\x52\x61\x72\x21\x1a\x07\x01\x00"; /** * List of block names corresponding to block types. - * * @var array */ protected $blockNames = array( // RAR 1.5 - 4.x - self::BLOCK_MARK => 'Marker', - self::BLOCK_MAIN => 'Archive', - self::BLOCK_FILE => 'File', - self::BLOCK_OLD_COMMENT => 'Old Style Comment', - self::BLOCK_OLD_EXTRA => 'Old Style Extra Info', - self::BLOCK_OLD_SUB => 'Old Style Subblock', - self::BLOCK_OLD_RECOVERY => 'Old Style Recovery Record', - self::BLOCK_OLD_AUTH => 'Old Style Archive Authenticity', - self::BLOCK_SUB => 'Subblock', - self::BLOCK_ENDARC => 'Archive End', - self::BLOCK_NULL => 'Null Block', + self::BLOCK_MARK => 'Marker', + self::BLOCK_MAIN => 'Archive', + self::BLOCK_FILE => 'File', + self::BLOCK_OLD_COMMENT => 'Old Style Comment', + self::BLOCK_OLD_EXTRA => 'Old Style Extra Info', + self::BLOCK_OLD_SUB => 'Old Style Subblock', + self::BLOCK_OLD_RECOVERY => 'Old Style Recovery Record', + self::BLOCK_OLD_AUTH => 'Old Style Archive Authenticity', + self::BLOCK_SUB => 'Subblock', + self::BLOCK_ENDARC => 'Archive End', + self::BLOCK_NULL => 'Null Block', // RAR 5.0 - self::R50_BLOCK_MAIN => 'Archive', - self::R50_BLOCK_FILE => 'File', - self::R50_BLOCK_SERVICE => 'Service', - self::R50_BLOCK_CRYPT => 'Archive Encryption', - self::R50_BLOCK_ENDARC => 'Archive End', + self::R50_BLOCK_MAIN => 'Archive', + self::R50_BLOCK_FILE => 'File', + self::R50_BLOCK_SERVICE => 'Service', + self::R50_BLOCK_CRYPT => 'Archive Encryption', + self::R50_BLOCK_ENDARC => 'Archive End', ); /** * List of the names corresponding to Subblock types (0x7a). - * * @var array */ protected $subblockNames = array( - self::SUBTYPE_COMMENT => 'Comment', - self::SUBTYPE_ACL => 'Access Control List', - self::SUBTYPE_STREAM => 'Stream', - self::SUBTYPE_UOWNER => 'Owner/Group Information', - self::SUBTYPE_AUTHVER => 'Authenticity Verification', - self::SUBTYPE_RECOVERY => 'Recovery Record', - self::SUBTYPE_OS2EA => 'OS2EA', - self::SUBTYPE_BEOSEA => 'BEOSEA', + self::SUBTYPE_COMMENT => 'Comment', + self::SUBTYPE_ACL => 'Access Control List', + self::SUBTYPE_STREAM => 'Stream', + self::SUBTYPE_UOWNER => 'Owner/Group Information', + self::SUBTYPE_AUTHVER => 'Authenticity Verification', + self::SUBTYPE_RECOVERY => 'Recovery Record', + self::SUBTYPE_OS2EA => 'OS2EA', + self::SUBTYPE_BEOSEA => 'BEOSEA', ); /** * List of the names corresponding to RAR 5.0 Service types. - * * @var array */ protected $serviceNames = array( - self::R50_SERVICE_COMMENT => 'Archive Comment', - self::R50_SERVICE_QUICKOPEN => 'Archive Quick Open', - self::R50_SERVICE_ACL => 'Access Control List', - self::R50_SERVICE_STREAM => 'NTFS Stream', - self::R50_SERVICE_RECOVERY => 'Recovery Record', + self::R50_SERVICE_COMMENT => 'Archive Comment', + self::R50_SERVICE_QUICKOPEN => 'Archive Quick Open', + self::R50_SERVICE_ACL => 'Access Control List', + self::R50_SERVICE_STREAM => 'NTFS Stream', + self::R50_SERVICE_RECOVERY => 'Recovery Record', ); /** * Is the volume attribute set for the archive? - * * @var boolean */ public $isVolume = false; /** * Is authenticity information present? - * * @var boolean */ public $hasAuth = false; /** * Is a recovery record present? - * * @var boolean */ public $hasRecovery = false; /** * Is the archive encrypted with a password? - * * @var boolean */ public $isEncrypted = false; /** * The RAR format version for the current archive. - * * @var string */ public $format = ''; /** * Any RAR 5.0 archive comments. - * * @var string */ public $comments = ''; @@ -363,22 +352,21 @@ class RarInfo extends ArchiveReader * Convenience method that outputs a summary list of the archive information, * useful for pretty-printing. * - * @param boolean $full add file list to output? - * @param boolean $skipDirs should directory entries be skipped? - * + * @param boolean $full add file list to output? + * @param boolean $skipDirs should directory entries be skipped? * @return array archive summary */ - public function getSummary($full = false, $skipDirs = false) + public function getSummary($full=false, $skipDirs=false) { $summary = array( 'file_name' => $this->file, 'file_size' => $this->fileSize, 'data_size' => $this->dataSize, 'use_range' => "{$this->start}-{$this->end}", - 'is_volume' => (int)$this->isVolume, - 'has_auth' => (int)$this->hasAuth, - 'has_recovery' => (int)$this->hasRecovery, - 'is_encrypted' => (int)$this->isEncrypted, + 'is_volume' => (int) $this->isVolume, + 'has_auth' => (int) $this->hasAuth, + 'has_recovery' => (int) $this->hasRecovery, + 'is_encrypted' => (int) $this->isEncrypted, 'rar_format' => $this->format, ); if ($this->comments) { @@ -400,27 +388,22 @@ class RarInfo extends ArchiveReader * Returns a list of the blocks found in the archive, optionally in human-readable * format (for debugging purposes only). * - * @param boolean $format should the block data be formatted? - * @param boolean $asHex should numeric values be displayed as hexadecimal? - * + * @param boolean $format should the block data be formatted? + * @param boolean $asHex should numeric values be displayed as hexadecimal? * @return array|boolean list of blocks, or false if none available */ - public function getBlocks($format = true, $asHex = false) + public function getBlocks($format=true, $asHex=false) { // Check that blocks are stored - if (empty($this->blocks)) { - return false; - } - if (!$format) { - return $this->blocks; - } + if (empty($this->blocks)) {return false;} + if (!$format) {return $this->blocks;} // Build a formatted block list $ret = array(); foreach ($this->blocks as $block) { $b = $this->formatBlock($block, $asHex); if ($b['head_type'] == self::R50_BLOCK_SERVICE && !empty($block['file_name']) - && $b['file_name'] == self::R50_SERVICE_QUICKOPEN + && $b['file_name'] == self::R50_SERVICE_QUICKOPEN ) { // Format any cached blocks foreach ($b['cache_data'] as &$cache) { @@ -437,20 +420,17 @@ class RarInfo extends ArchiveReader * Parses the stored blocks and returns a list of records for each of the * files in the archive. * - * @param boolean $skipDirs should directory entries be skipped? - * + * @param boolean $skipDirs should directory entries be skipped? * @return array list of file records, empty if none are available */ - public function getFileList($skipDirs = false) + public function getFileList($skipDirs=false) { $ret = array(); foreach ($this->blocks as $block) { if (($block['head_type'] == self::BLOCK_FILE || $block['head_type'] == self::R50_BLOCK_FILE) - && !empty($block['file_name']) + && !empty($block['file_name']) ) { - if ($skipDirs && !empty($block['is_dir'])) { - continue; - } + if ($skipDirs && !empty($block['is_dir'])) {continue;} $ret[] = $this->getFileBlockSummary($block); } } @@ -461,28 +441,23 @@ class RarInfo extends ArchiveReader /** * Returns a summary list of any RAR 5.0 Quick Open cached file headers. * - * @param boolean $skipDirs should directory entries be skipped? - * + * @param boolean $skipDirs should directory entries be skipped? * @return array|boolean list of file record, or false if none available */ - public function getQuickOpenFileList($skipDirs = false) + public function getQuickOpenFileList($skipDirs=false) { // Check that blocks are stored - if (empty($this->blocks)) { - return false; - } + if (empty($this->blocks)) {return false;} $ret = array(); foreach ($this->blocks as $block) { if ($block['head_type'] == self::R50_BLOCK_SERVICE && !empty($block['file_name']) - && $block['file_name'] == self::R50_SERVICE_QUICKOPEN + && $block['file_name'] == self::R50_SERVICE_QUICKOPEN ) { // Build the cached file header list foreach ($block['cache_data'] as $cache) { if ($cache['data']['head_type'] == self::R50_BLOCK_FILE) { - if ($skipDirs && !empty($cache['data']['is_dir'])) { - continue; - } + if ($skipDirs && !empty($cache['data']['is_dir'])) {continue;} $ret[] = $this->getFileBlockSummary($cache['data'], true); } } @@ -496,8 +471,7 @@ class RarInfo extends ArchiveReader * Retrieves the raw data for the given filename. Note that this is only useful * if the file isn't compressed. * - * @param string $filename name of the file to extract - * + * @param string $filename name of the file to extract * @return string|boolean file data, or false on error */ public function getFileData($filename) @@ -509,7 +483,6 @@ class RarInfo extends ArchiveReader // Get the absolute start/end positions if (!($info = $this->getFileInfo($filename)) || empty($info['range'])) { $this->error = "Could not find file info for: ({$filename})"; - return false; } $this->error = ''; @@ -521,9 +494,8 @@ class RarInfo extends ArchiveReader * Saves the raw data for the given filename to the given destination. This * is only useful if the file isn't compressed. * - * @param string $filename name of the file to extract - * @param string $destination full path of the file to create - * + * @param string $filename name of the file to extract + * @param string $destination full path of the file to create * @return integer|boolean number of bytes saved or false on error */ public function saveFileData($filename, $destination) @@ -535,7 +507,6 @@ class RarInfo extends ArchiveReader // Get the absolute start/end positions if (!($info = $this->getFileInfo($filename)) || empty($info['range'])) { $this->error = "Could not find file info for: ({$filename})"; - return false; } $this->error = ''; @@ -546,8 +517,7 @@ class RarInfo extends ArchiveReader /** * Sets the absolute path to the external Unrar client. * - * @param string $client path to the client - * + * @param string $client path to the client * @return void * @throws InvalidArgumentException */ @@ -563,29 +533,25 @@ class RarInfo extends ArchiveReader * Extracts a compressed or encrypted file using the configured external Unrar * client, optionally returning the data or saving it to file. * - * @param string $filename name of the file to extract - * @param string $destination full path of the file to create - * @param string $password password to use for decryption - * + * @param string $filename name of the file to extract + * @param string $destination full path of the file to create + * @param string $password password to use for decryption * @return mixed extracted data, number of bytes saved or false on error */ - public function extractFile($filename, $destination = null, $password = null) + public function extractFile($filename, $destination=null, $password=null) { if (!$this->externalClient || (!$this->file && !$this->data)) { $this->error = 'An external client and valid data source are needed'; - return false; } // Check that the file is extractable if (!($info = $this->getFileInfo($filename))) { $this->error = "Could not find file info for: ({$filename})"; - return false; } if (!empty($info['pass']) && $password == null) { $this->error = "The file is passworded: ({$filename})"; - return false; } @@ -598,21 +564,20 @@ class RarInfo extends ArchiveReader } // Set the external command - $pass = $password ? '-p' . escapeshellarg($password) : '-p-'; - $command = '"' . $this->externalClient . '"' - . " p -kb -y -c- -ierr -ip {$pass} -- " - . escapeshellarg($source) . ' ' . escapeshellarg($filename); + $pass = $password ? '-p'.escapeshellarg($password) : '-p-'; + $command = '"'.$this->externalClient.'"' + ." p -kb -y -c- -ierr -ip {$pass} -- " + .escapeshellarg($source).' '.escapeshellarg($filename); // Set STDERR to write to a temporary file - list($hash, $errorFile) = $this->getTempFileName($source . 'errors'); + list($hash, $errorFile) = $this->getTempFileName($source.'errors'); $this->tempFiles[$hash] = $errorFile; - $command .= ' 2> ' . escapeshellarg($errorFile); + $command .= ' 2> '.escapeshellarg($errorFile); // Start the new pipe reader $pipe = new PipeReader; if (!$pipe->open($command)) { $this->error = $pipe->error; - return false; } $this->error = ''; @@ -633,18 +598,13 @@ class RarInfo extends ArchiveReader $data .= $read; } } - if ($destination) { - fclose($handle); - } + if ($destination) {fclose($handle);} $pipe->close(); // Check for errors (only after the pipe is closed) if (($error = @file_get_contents($errorFile)) && strpos($error, 'All OK') === false) { - if ($destination) { - @unlink($destination); - } + if ($destination) {@unlink($destination);} $this->error = $error; - return false; } @@ -653,7 +613,6 @@ class RarInfo extends ArchiveReader /** * List of block types and Subblock subtypes without bodies. - * * @var array */ protected $headersOnly = array( @@ -663,14 +622,12 @@ class RarInfo extends ArchiveReader /** * List of blocks found in the archive. - * * @var array */ protected $blocks = array(); /** * Full path to the external Unrar client. - * * @var string */ protected $externalClient = ''; @@ -678,24 +635,23 @@ class RarInfo extends ArchiveReader /** * Returns block data in human-readable format (for debugging purposes only). * - * @param array $block the block to format - * @param boolean $asHex should numeric values be displayed as hexadecimal? - * + * @param array $block the block to format + * @param boolean $asHex should numeric values be displayed as hexadecimal? * @return array the formatted block */ - protected function formatBlock($block, $asHex = false) + protected function formatBlock($block, $asHex=false) { $b = array(); // Add block descriptors $b['type'] = isset($this->blockNames[$block['head_type']]) ? $this->blockNames[$block['head_type']] : 'Unknown'; if ($block['head_type'] == self::BLOCK_SUB && !empty($block['file_name']) - && isset($this->subblockNames[$block['file_name']]) + && isset($this->subblockNames[$block['file_name']]) ) { $b['sub_type'] = $this->subblockNames[$block['file_name']]; } if ($block['head_type'] == self::R50_BLOCK_SERVICE && !empty($block['file_name']) - && isset($this->serviceNames[$block['file_name']]) + && isset($this->serviceNames[$block['file_name']]) ) { $b['name'] = $this->serviceNames[$block['file_name']]; } @@ -717,26 +673,25 @@ class RarInfo extends ArchiveReader /** * Returns a processed summary of a RAR File block. * - * @param array $block a valid File block - * @param array $quickOpen is this a Quick Open cached block? - * + * @param array $block a valid File block + * @param array $quickOpen is this a Quick Open cached block? * @return array summary information */ - protected function getFileBlockSummary($block, $quickOpen = false) + protected function getFileBlockSummary($block, $quickOpen=false) { $ret = array( - 'name' => !empty($block['file_name']) ? substr($block['file_name'], 0, $this->maxFilenameLength) : 'Unknown', - 'size' => isset($block['unp_size']) ? $block['unp_size'] : 0, - 'date' => !empty($block['utime']) ? $block['utime'] : (!empty($block['ftime']) ? self::dos2unixtime($block['ftime']) : 0), - 'pass' => isset($block['has_password']) ? ((int)$block['has_password']) : 0, - 'compressed' => (int)($block['method'] != self::METHOD_STORE && $block['method'] != self::R50_METHOD_STORE), + 'name' => !empty($block['file_name']) ? substr($block['file_name'], 0, $this->maxFilenameLength) : 'Unknown', + 'size' => isset($block['unp_size']) ? $block['unp_size'] : 0, + 'date' => !empty($block['utime']) ? $block['utime'] : (!empty($block['ftime']) ? self::dos2unixtime($block['ftime']) : 0), + 'pass' => isset($block['has_password']) ? ((int) $block['has_password']) : 0, + 'compressed' => (int) ($block['method'] != self::METHOD_STORE && $block['method'] != self::R50_METHOD_STORE), 'next_offset' => $block['next_offset'], ); if (!empty($block['is_dir'])) { $ret['is_dir'] = 1; } elseif (!$quickOpen && !in_array(self::BLOCK_FILE, $this->headersOnly['type'])) { $start = $this->start + $block['offset'] + $block['head_size']; - $end = min($this->end, $start + $block['pack_size'] - 1); + $end = min($this->end, $start + $block['pack_size'] - 1); $ret['range'] = "{$start}-{$end}"; } if (!empty($block['file_crc'])) { @@ -755,8 +710,7 @@ class RarInfo extends ArchiveReader /** * Returns information for the given filename in the current file/data. * - * @param string $filename the filename to search - * + * @param string $filename the filename to search * @return array|boolean the file info or false on error */ protected function getFileInfo($filename) @@ -766,7 +720,6 @@ class RarInfo extends ArchiveReader return $file; } } - return false; } @@ -786,9 +739,7 @@ class RarInfo extends ArchiveReader try { $buffer = $this->read(min($this->length, $this->maxReadBytes)); $this->rewind(); - } catch (Exception $e) { - return false; - } + } catch (Exception $e) {return false;} // Get all the offsets to test if (!($positions = self::strposall($buffer, pack('C', self::BLOCK_FILE)))) @@ -807,15 +758,12 @@ class RarInfo extends ArchiveReader // A valid File header was found $this->format = self::FMT_RAR15; - return $this->markerPosition = $block['offset']; } } - // No more readable data, or read error - } catch (Exception $e) { - continue; - } + // No more readable data, or read error + } catch (Exception $e) {continue;} return false; } @@ -823,24 +771,20 @@ class RarInfo extends ArchiveReader /** * Runs a File Header CRC check on a valid File block. * - * @param array $block a valid File block - * + * @param array $block a valid File block * @return boolean false if CRC check fails */ protected function checkFileHeaderCRC($block) { // Not supported for RAR 5.0 - if ($this->format == self::FMT_RAR50) { - return false; - } + if ($this->format == self::FMT_RAR50) {return false;} try { $this->seek($block['offset'] + 2); $data = $this->read($block['head_size'] - 2); $crc = crc32($data) & 0xffff; - return ($crc === $block['head_crc']); - } catch (Exception $e) { + } catch (Exception $e){ return false; } } @@ -849,24 +793,21 @@ class RarInfo extends ArchiveReader * File header CRC checks can produce false positives, so this is a * last-ditch attempt to verify that this is actually a valid header. * - * @param array $block the block to sanity check - * @param integer $limit the minimum failure threshold - * + * @param array $block the block to sanity check + * @param integer $limit the minimum failure threshold * @return boolean false if the sanity check fails */ - protected function sanityCheckFileHeader($block, $limit = 3) + protected function sanityCheckFileHeader($block, $limit=3) { // Not supported for RAR 5.0 - if ($this->format == self::FMT_RAR50) { - return false; - } + if ($this->format == self::FMT_RAR50) {return false;} $fail = ($block['host_os'] > 5) - + ($block['method'] > 0x35) - + ($block['unp_ver'] > 50) - + ($block['name_size'] > $this->maxFilenameLength) - + ($block['pack_size'] > PHP_INT_MAX) - + (isset($block['salt']) && !isset($block['has_password'])); + + ($block['method'] > 0x35) + + ($block['unp_ver'] > 50) + + ($block['name_size'] > $this->maxFilenameLength) + + ($block['pack_size'] > PHP_INT_MAX) + + (isset($block['salt']) && !isset($block['has_password'])); return $fail < $limit; } @@ -889,7 +830,6 @@ class RarInfo extends ArchiveReader } elseif (($pos = strpos($buff, $this->markerRar50)) !== false) { $this->format = self::FMT_RAR50; } - return $this->markerPosition = $pos; } catch (Exception $e) { return false; @@ -905,7 +845,8 @@ class RarInfo extends ArchiveReader { // Find the RAR marker, if there is one $startPos = $this->findMarker(); - if ($this->format == self::FMT_RAR50) { + if ($this->format == self::FMT_RAR50) + { // Start after the RAR 5.0 marker signature $this->seek($startPos + strlen($this->markerRar50)); @@ -913,7 +854,6 @@ class RarInfo extends ArchiveReader // Not a RAR fragment or valid file, so abort here $this->error = 'Could not find Marker block, not a valid RAR file'; - return false; } elseif ($startPos !== false) { @@ -926,7 +866,6 @@ class RarInfo extends ArchiveReader // Search for a valid file header and continue unpacking from there if (($startPos = $this->findFileHeader()) === false) { $this->error = 'Could not find a valid File header'; - return false; } $this->seek($startPos); @@ -957,24 +896,18 @@ class RarInfo extends ArchiveReader if ($block['offset'] == $this->offset) { $this->error = 'Parsing seems to be stuck'; $this->close(); - return false; } - // No more readable data, or read error + // No more readable data, or read error } catch (Exception $e) { - if ($this->error) { - $this->close(); - - return false; - } + if ($this->error) {$this->close(); return false;} break; } // Check for valid blocks if (empty($this->blocks)) { $this->error = 'No valid RAR blocks were found'; - return false; } @@ -1001,8 +934,8 @@ class RarInfo extends ArchiveReader // Check for add_size field if (($block['head_flags'] & self::LONG_BLOCK) - && ($block['head_type'] != self::BLOCK_FILE) - && ($block['head_type'] != self::BLOCK_SUB) + && ($block['head_type'] != self::BLOCK_FILE) + && ($block['head_type'] != self::BLOCK_SUB) ) { $block += self::unpack('Vadd_size', $this->read(4)); } else { @@ -1022,8 +955,7 @@ class RarInfo extends ArchiveReader /** * Processes a block passed by reference based on its type. * - * @param array $block the block to process - * + * @param array $block the block to process * @return void */ protected function processBlock(&$block) @@ -1054,17 +986,23 @@ class RarInfo extends ArchiveReader $block['is_encrypted'] = 1; $this->isEncrypted = true; } - } // Block type: ARCHIVE END + } + + // Block type: ARCHIVE END elseif ($block['head_type'] == self::BLOCK_ENDARC) { - $block['more_volumes'] = (bool)($block['head_flags'] & self::ENDARC_NEXT_VOLUME); - } // Block type: NULL BLOCK (zero-padded) + $block['more_volumes'] = (bool) ($block['head_flags'] & self::ENDARC_NEXT_VOLUME); + } + + // Block type: NULL BLOCK (zero-padded) elseif ($block['head_type'] == self::BLOCK_NULL) { $remainder = $this->length - $block['offset'] - $block['head_size']; if ($remainder < self::HEADER_SIZE) { $block['next_offset'] = $this->length; $block['add_size'] = $remainder; } - } // Block type: FILE or SUBBLOCK (new style) + } + + // Block type: FILE or SUBBLOCK (new style) elseif ($block['head_type'] == self::BLOCK_FILE || $block['head_type'] == self::BLOCK_SUB) { // Unpack the remainder of the block header @@ -1093,12 +1031,12 @@ class RarInfo extends ArchiveReader if ($ucname = $uc->decode()) { $block['file_name'] = @iconv('UTF-16LE', 'UTF-8//IGNORE//TRANSLIT', $ucname); - // Fallback to the standard filename + // Fallback to the standard filename } else { $block['file_name'] = $fn[0]; } - // Filename: non-unicode + // Filename: non-unicode } else { $block['file_name'] = $this->read($block['name_size']); } @@ -1135,7 +1073,7 @@ class RarInfo extends ArchiveReader // Update next header block offset if (($block['head_type'] == self::BLOCK_FILE && !in_array(self::BLOCK_FILE, $this->headersOnly['type'])) - || ($block['head_type'] == self::BLOCK_SUB && !in_array($block['file_name'], $this->headersOnly['subtype'])) + || ($block['head_type'] == self::BLOCK_SUB && !in_array($block['file_name'], $this->headersOnly['subtype'])) ) { $block['next_offset'] += $block['pack_size']; } @@ -1168,9 +1106,9 @@ class RarInfo extends ArchiveReader // Unpack the main part of the header $block += self::unpack('Vhead_crc', $this->read(4)); $block['head_size_r'] = $this->getVarInt(); - $block['head_size'] = $this->offset - $block['offset'] + $block['head_size_r']; - $block['head_type'] = $this->getVarInt(); - $block['head_flags'] = $this->getVarInt(); + $block['head_size'] = $this->offset - $block['offset'] + $block['head_size_r']; + $block['head_type'] = $this->getVarInt(); + $block['head_flags'] = $this->getVarInt(); // Optional extra area and data area sizes if ($block['head_flags'] & self::R50_HAS_EXTRA) { @@ -1196,13 +1134,12 @@ class RarInfo extends ArchiveReader /** * Processes a RAR 5.0 block passed by reference based on its type. * - * @param array $block the block to process - * @param array $quickOpen is this a Quick Open cached block? - * + * @param array $block the block to process + * @param array $quickOpen is this a Quick Open cached block? * @return void * @throws RuntimeException */ - protected function processBlockR50(&$block, $quickOpen = false) + protected function processBlockR50(&$block, $quickOpen=false) { // Block type: ARCHIVE if ($block['head_type'] == self::R50_BLOCK_MAIN) { @@ -1219,25 +1156,31 @@ class RarInfo extends ArchiveReader $block['has_recovery'] = true; $this->hasRecovery = true; } - } // Block type: ARCHIVE END + } + + // Block type: ARCHIVE END elseif ($block['head_type'] == self::R50_BLOCK_ENDARC) { $block['flags'] = $this->getVarInt(); - $block['more_volumes'] = (bool)($block['flags'] & self::R50_ENDARC_NEXT_VOLUME); - } // Block type: ARCHIVE ENCRYPTION + $block['more_volumes'] = (bool) ($block['flags'] & self::R50_ENDARC_NEXT_VOLUME); + } + + // Block type: ARCHIVE ENCRYPTION elseif ($block['head_type'] == self::R50_BLOCK_CRYPT) { $this->isEncrypted = true; - } // Block type: FILE or SERVICE + } + + // Block type: FILE or SERVICE elseif ($block['head_type'] == self::R50_BLOCK_FILE - || $block['head_type'] == self::R50_BLOCK_SERVICE + || $block['head_type'] == self::R50_BLOCK_SERVICE ) { if (!isset($block['data_size'])) throw new RuntimeException('Required block data size is missing'); - $block['flags'] = $this->getVarInt(); + $block['flags'] = $this->getVarInt(); $block['pack_size'] = $block['data_size']; - $block['unp_size'] = $this->getVarInt(); - $block['attr'] = $this->getVarInt(); - $block['utime'] = 0; + $block['unp_size'] = $this->getVarInt(); + $block['attr'] = $this->getVarInt(); + $block['utime'] = 0; if ($block['flags'] & self::R50_FILE_UTIME) { $block += self::unpack('Vutime', $this->read(4)); @@ -1250,9 +1193,9 @@ class RarInfo extends ArchiveReader } $block['comp_info'] = $this->getVarInt(); - $block['unp_ver'] = $block['comp_info'] & 0x3f; - $block['method'] = ($block['comp_info'] >> 7) & 7; - $block['host_os'] = $this->getVarInt(); + $block['unp_ver'] = $block['comp_info'] & 0x3f; + $block['method'] = ($block['comp_info'] >> 7) & 7; + $block['host_os'] = $this->getVarInt(); $block['name_size'] = $this->getVarInt(); $block['file_name'] = $this->read($block['name_size']); @@ -1267,7 +1210,7 @@ class RarInfo extends ArchiveReader if ($block['file_name'] == self::R50_SERVICE_COMMENT) { $this->comments = $this->read($block['pack_size']); - // Add the quick open data + // Add the quick open data } elseif ($block['file_name'] == self::R50_SERVICE_QUICKOPEN) { $this->processQuickOpenRecords($block); } @@ -1293,8 +1236,7 @@ class RarInfo extends ArchiveReader /** * Processes the RAR 5.0 Quick Open block data and stores any cached headers. * - * @param array $block the block to process - * + * @param array $block the block to process * @return void */ protected function processQuickOpenRecords(&$block) @@ -1305,11 +1247,11 @@ class RarInfo extends ArchiveReader // Start the cache record $cache = array('offset' => $this->offset); $cache += self::unpack('Vcrc32', $this->read(4)); - $cache['size'] = $this->getVarInt(); - $cache['flags'] = $this->getVarInt(); + $cache['size'] = $this->getVarInt(); + $cache['flags'] = $this->getVarInt(); $cache['quick_offset'] = $this->getVarInt(); - $cache['data_size'] = $this->getVarInt(); - $cache['next'] = $this->offset + $cache['data_size']; + $cache['data_size'] = $this->getVarInt(); + $cache['next'] = $this->offset + $cache['data_size']; // Process the cached header data $data = $this->getNextBlockR50(); @@ -1327,8 +1269,7 @@ class RarInfo extends ArchiveReader /** * Processes the extra records of a RAR 5.0 block passed by reference. * - * @param array $block the block to process - * + * @param array $block the block to process * @return void */ protected function processExtraRecords(&$block) @@ -1348,7 +1289,7 @@ class RarInfo extends ArchiveReader // Block type: ARCHIVE if ($block['head_type'] == self::R50_BLOCK_MAIN) { if ($rec['type'] == self::R50_MEXTRA_LOCATOR) { - $rec['name'] = 'Locator'; + $rec['name'] = 'Locator'; $rec['flags'] = $this->getVarInt(); if ($rec['flags'] & self::R50_MEXTRA_LOC_QLIST) { @@ -1358,17 +1299,21 @@ class RarInfo extends ArchiveReader $rec['rr'] = $this->getVarInt(); } } - } // Block type: FILE + } + + // Block type: FILE elseif ($block['head_type'] == self::R50_BLOCK_FILE) { if ($rec['type'] == self::R50_FEXTRA_CRYPT) { $rec['name'] = 'File encryption'; $block['has_password'] = true; - } elseif ($rec['type'] == self::R50_FEXTRA_HASH) { + } + elseif ($rec['type'] == self::R50_FEXTRA_HASH) { $rec['name'] = 'File hash'; - } elseif ($rec['type'] == self::R50_FEXTRA_HTIME) { - $rec['name'] = 'File time'; + } + elseif ($rec['type'] == self::R50_FEXTRA_HTIME) { + $rec['name'] = 'File time'; $rec['flags'] = $this->getVarInt(); - $rec['unix'] = (bool)($rec['flags'] & self::R50_FEXTRA_HT_UNIX); + $rec['unix'] = (bool) ($rec['flags'] & self::R50_FEXTRA_HT_UNIX); if ($rec['flags'] & self::R50_FEXTRA_HT_MTIME) { if ($rec['unix']) { @@ -1393,13 +1338,17 @@ class RarInfo extends ArchiveReader $rec += self::unpack('Vatime/Vatime_high', $this->read(8)); } } - } elseif ($rec['type'] == self::R50_FEXTRA_VERSION) { + } + elseif ($rec['type'] == self::R50_FEXTRA_VERSION) { $rec['name'] = 'File version'; - } elseif ($rec['type'] == self::R50_FEXTRA_REDIR) { + } + elseif ($rec['type'] == self::R50_FEXTRA_REDIR) { $rec['name'] = 'Redirection'; - } elseif ($rec['type'] == self::R50_FEXTRA_UOWNER) { + } + elseif ($rec['type'] == self::R50_FEXTRA_UOWNER) { $rec['name'] = 'Unix owner'; - } elseif ($rec['type'] == self::R50_FEXTRA_SUBDATA) { + } + elseif ($rec['type'] == self::R50_FEXTRA_SUBDATA) { $rec['name'] = 'Service data'; } } @@ -1430,22 +1379,17 @@ class RarInfo extends ArchiveReader while ($this->offset < $this->length && $count <= 10) { $byte = ord($this->read(1)); if ($count < 5) { - $low += ($byte & 0x7f) << $shift; + $low += ($byte & 0x7f) << $shift; } elseif ($count == 5) { - $low += ($byte & 0x0f) << $shift; // 4 bits - $high += ($byte >> 4) & 0x07; // 3 bits + $low += ($byte & 0x0f) << $shift; // 4 bits + $high += ($byte >> 4) & 0x07; // 3 bits $shift = -4; } elseif ($count > 5) { $high += ($byte & 0x7f) << $shift; } if (($byte & 0x80) === 0) { - if ($low < 0) { - $low += 0x100000000; - } - if ($high < 0) { - $high += 0x100000000; - } - + if ($low < 0) {$low += 0x100000000;} + if ($high < 0) {$high += 0x100000000;} return ($high ? self::int64($low, $high) : $low); } $shift += 7; @@ -1480,7 +1424,7 @@ class RarInfo extends ArchiveReader * This utility class handles the unicode filename decompression for RAR files. It is * adapted directly from Marko Kreen's python script rarfile.py. * - * @link https://github.com/markokr/rarfile + * @link https://github.com/markokr/rarfile * * @version 1.2 */ @@ -1489,9 +1433,8 @@ class RarUnicodeFilename /** * Initializes the class instance. * - * @param string $stdName the standard filename - * @param string $encData the unicode data - * + * @param string $stdName the standard filename + * @param string $encData the unicode data * @return void */ public function __construct($stdName, $encData) @@ -1546,51 +1489,42 @@ class RarUnicodeFilename } // Return the unicode string - if ($this->failed) { - return false; - } - + if ($this->failed) {return false;} return $this->output; } /** * The standard filename data. - * * @var string */ protected $stdName; /** * The unicode data used for processing. - * * @var string */ protected $encData; /** * Pointer for the standard filename data. - * * @var integer */ protected $pos = 0; /** * Pointer for the unicode data. - * * @var integer */ protected $encPos = 0; /** * Did the decompression fail? - * * @var boolean */ protected $failed = false; /** * Decompressed unicode filename string. - * * @var string */ protected $output; @@ -1610,7 +1544,6 @@ class RarUnicodeFilename $ret = 0; } $this->encPos++; - return $ret; } @@ -1625,16 +1558,14 @@ class RarUnicodeFilename return ord($this->stdName[$this->pos]); } $this->failed = true; - return ord('?'); } /** * Builds the output for the unicode filename string in 16-bit blocks (UTF-16LE). * - * @param integer $low low byte value - * @param integer $high high byte value - * + * @param integer $low low byte value + * @param integer $high high byte value * @return void */ protected function put($low, $high) @@ -1644,4 +1575,4 @@ class RarUnicodeFilename $this->pos++; } -} // End RarUnicodeFilename class \ No newline at end of file +} // End RarUnicodeFilename class diff --git a/lib/copy_this/libs/rarinfo/sfvinfo.php b/lib/copy_this/libs/rarinfo/sfvinfo.php new file mode 100644 index 000000000..3e6615600 --- /dev/null +++ b/lib/copy_this/libs/rarinfo/sfvinfo.php @@ -0,0 +1,167 @@ + + * + * // Load the SFV file or data + * $sfv = new SfvInfo; + * $sfv->open('./foo.sfv'); // or $sfv->setData($data); + * if ($sfv->error) { + * echo "Error: {$sfv->error}\n"; + * exit; + * } + * + * // Process the file list + * $files = $sfv->getFileList(); + * foreach ($files as $file) { + * echo $file['name'].' - '.$file['checksum']; + * } + * + * + * + * @author Hecks + * @copyright (c) 2010-2013 Hecks + * @license Modified BSD + * @version 2.1 + */ +class SfvInfo extends ArchiveReader +{ + /** + * SFV file comments. + * @var string + */ + public $comments = ''; + + /** + * Convenience method that outputs a summary list of the SFV file records, + * useful for pretty-printing. + * + * @param boolean $basenames don't include full file paths? + * @return array file record summary + */ + public function getSummary($full=false, $basenames=false) + { + $summary = array( + 'file_name' => $this->file, + 'file_size' => $this->fileSize, + 'data_size' => $this->dataSize, + 'use_range' => "{$this->start}-{$this->end}", + 'file_count' => $this->fileCount, + ); + if ($full) { + $summary['file_list'] = $this->getFileList($basenames); + } + if ($this->error) { + $summary['error'] = $this->error; + } + + return $summary; + } + + /** + * Returns a list of file records with checksums from the source SFV file. + * + * @param boolean $basenames don't include full file paths? + * @return array list of file records, empty if none are available + */ + public function getFileList($basenames=false) + { + if ($basenames) { + $ret = array(); + foreach ($this->fileList as $item) { + $item['name'] = pathinfo($item['name'], PATHINFO_BASENAME); + $ret[] = $item; + } + return $ret; + } + + return $this->fileList; + } + + /** + * Returns the position of the archive marker/signature. + * + * @return mixed Marker position, or false if none found + */ + public function findMarker() + { + return $this->markerPosition = 0; + } + + /** + * The parsed file list with checksum info. + * @var array + */ + protected $fileList = array(); + + /** + * Parses the source data and stores a list of valid file records locally. + * + * @return boolean false if parsing fails + */ + protected function analyze() + { + // Get the available data up to the maximum allowed + try { + $data = $this->read(min($this->length, $this->maxReadBytes)); + } catch (Exception $e) { + $this->close(); + return false; + } + + // Split on all line ending types + foreach (preg_split('/\R/', $data, -1, PREG_SPLIT_NO_EMPTY) as $line) { + + // Store comment lines + if (strpos($line, ';') === 0) { + $this->comments .= trim(substr($line, 1))."\n"; + continue; + } + + if (preg_match('/^(.+?)\s+([[:xdigit:]]{2,8})$/', trim($line), $matches)) { + + // Store the file record locally + $this->fileList[] = array( + 'name' => $matches[1], + 'checksum' => $matches[2] + ); + + // Increment the filecount + $this->fileCount++; + + } else { + + // Contains invalid chars, so assume this isn't an SFV + $this->error = 'Not a valid SFV file'; + $this->close(); + return false; + } + } + + // Analysis was successful + $this->close(); + return true; + } + + /** + * Resets the instance variables before parsing new data. + * + * @return void + */ + protected function reset() + { + parent::reset(); + $this->fileList = array(); + $this->comments = ''; + } + +} // End SfvInfo class diff --git a/lib/copy_this/libs/rarinfo/srrinfo.php b/lib/copy_this/libs/rarinfo/srrinfo.php new file mode 100644 index 000000000..d0f9259ca --- /dev/null +++ b/lib/copy_this/libs/rarinfo/srrinfo.php @@ -0,0 +1,332 @@ + + * + * // Load the SRR file or data + * $srr = new SrrInfo; + * $srr->open('./foo.srr'); // or $srr->setData($data); + * if ($srr->error) { + * echo "Error: {$srr->error}\n"; + * exit; + * } + * + * // Get any SRR stored files + * $stored = $srr->getStoredFiles(); + * foreach ($stored as $file) { + * echo "{$file['name']} ({$file['size']}):\n"; + * echo $file['data']; + * } + * + * // Inspect the RAR file list + * $volumes = $srr->getFileList(); + * foreach ($volumes as $vol) { + * echo "Archive volume: {$vol['name']}\n"; + * foreach ($vol['files'] as $file) { + * if ($file['pass'] == true) { + * echo "-- File is passworded: {$file['name']}\n"; + * } + * } + * } + * + * + * + * @author Hecks + * @copyright (c) 2010-2013 Hecks + * @license Modified BSD + * @version 2.3 + */ +class SrrInfo extends RarInfo +{ + // ------ Class constants ----------------------------------------------------- + + /**#@+ + * SRR file format values + */ + + // SRR Block types + const SRR_BLOCK_MARK = 0x69; + const SRR_STORED_FILE = 0x6a; + const SRR_OSO_HASH = 0x6b; + const SRR_RAR_FILE = 0x71; + + // Flags for SRR Marker block + const APP_NAME_PRESENT = 0x0001; + + /**#@-*/ + + /** + * Format for unpacking any OSO hash blocks. + */ + const FORMAT_SRR_OSO_HASH = 'Vfile_size/Vfile_size_high/h16file_hash/vname_size'; + + + // ------ Instance variables and methods --------------------------------------- + + /** + * Signature for the SRR Marker block. + * @var string + */ + protected $markerBlock = "\x69\x69\x69"; + + /** + * List of block names corresponding to SRR block types. + * @var array + */ + protected $srrBlockNames = array( + self::SRR_BLOCK_MARK => 'SRR Marker', + self::SRR_STORED_FILE => 'Stored File', + self::SRR_OSO_HASH => 'OSO Hash', + self::SRR_RAR_FILE => 'RAR File', + ); + + /** + * List of block types and Subblock subtypes without bodies. + * @var array + */ + protected $headersOnly = array( + 'type' => array(self::BLOCK_FILE), + 'subtype' => array(self::SUBTYPE_RECOVERY), + ); + + /** + * Details of the client that created the file/data. + * @var string + */ + public $client = ''; + + /** + * Initializes the class instance. + * + * @return void + */ + public function __construct($file=null, $isFragment=false, array $range=null) + { + // Merge the SRR and RAR block names + $this->blockNames = $this->srrBlockNames + $this->blockNames; + + parent::__construct($file, $isFragment, $range); + } + + /** + * Convenience method that outputs a summary list of the SRR information, + * useful for pretty-printing. + * + * @param boolean $full include full info, e.g. stored file data? + * @param boolean $skipDirs should RAR directory entries be skipped? + * @return array SRR file summary + */ + public function getSummary($full=false, $skipDirs=false) + { + $summary = array( + 'file_name' => $this->file, + 'file_size' => $this->fileSize, + 'data_size' => $this->dataSize, + 'client' => $this->client, + 'stored_files' => $this->getStoredFiles($full), + ); + if ($osoInfo = $this->getOsoInfo()) { + $summary['oso_info'] = $osoInfo; + } + $fileList = $this->getFileList($skipDirs); + $summary['file_count'] = count($fileList); + if ($full) { + $summary['file_list'] = $fileList; + } + if ($this->error) { + $summary['error'] = $this->error; + } + + return $summary; + } + + /** + * Parses the stored blocks and returns a list of the Stored File records, + * optionally with the file content data included. + * + * @param boolean $extract include file data in the result? + * @return mixed false if no stored files blocks available, or array of records + */ + public function getStoredFiles($extract=true) + { + if (empty($this->blocks)) {return false;} + $ret = array(); + + foreach ($this->blocks as $block) { + if ($block['head_type'] == self::SRR_STORED_FILE) { + $b = array( + 'name' => $block['file_name'], + 'size' => (isset($block['add_size']) ? $block['add_size'] : 0), + ); + if ($extract) { + $b['data'] = $block['file_data']; + } + $ret[] = $b; + } + } + + return $ret; + } + + /** + * Parses the stored blocks and returns summary info of any OSO hash block + * in the SRR file/data. + * + * @link http://trac.opensubtitles.org/projects/opensubtitles/wiki/HashSourceCodes + * + * @return array|boolean OSO info, or false if none is available + */ + public function getOsoInfo() + { + if (empty($this->blocks)) {return false;} + + foreach ($this->blocks as $block) { + if ($block['head_type'] == self::SRR_OSO_HASH) { + return array( + 'name' => $block['file_name'], + 'size' => $block['file_size'], + 'hash' => $block['file_hash'], + ); + } + } + + return false; + } + + /** + * Parses the stored blocks and returns a list of the RAR volume records that the + * SRR data covers. + * + * @param boolean $skipDirs should directory entries be skipped? + * @return array|boolean list of file records, or false if none are available + */ + public function getFileList($skipDirs=false) + { + $list = array(); + $i = -1; + + foreach ($this->blocks as $block) { + + // Start a new RAR volume record + if ($block['head_type'] == self::SRR_RAR_FILE) { + $list[++$i] = array('name' => $block['file_name']); + + // Append the file summaries to the current volume record + } elseif ($block['head_type'] == self::BLOCK_FILE) { + if ($skipDirs && !empty($block['is_dir'])) {continue;} + $list[$i]['files'][] = $this->getFileBlockSummary($block); + } + } + + return $list; + } + + // SRR files do not include any file contents + public function getFileData($filename) {return false;} + public function saveFileData($filename, $destination) {return false;} + public function extractFile($filename, $destination=null, $password=null) {return false;} + + /** + * Parses the SRR data and stores a list of valid blocks locally. + * + * @return boolean false if parsing fails + */ + protected function analyze() + { + // Find the SRR MARKER block, or abort if none is found + if (($startPos = $this->findMarker()) === false) { + $this->error = 'Could not find Marker block, not a valid SRR file'; + return false; + } + + // Start at the SRR MARKER block + $this->seek($startPos); + + // Analyze all valid blocks + while ($this->offset < $this->length) try { + + // Get the next block header + $block = $this->getNextBlock(); + + // Block type: SRR MARKER + if ($block['head_type'] == self::SRR_BLOCK_MARK) { + if ($block['head_flags'] & self::APP_NAME_PRESENT) { + $block += self::unpack('vapp_name_size', $this->read(2), false); + $block['app_name'] = $this->read($block['app_name_size']); + $this->client = $block['app_name']; + } + if ($block['head_flags'] > 1 || $this->offset != $block['next_offset']) { + $this->error = 'Could not find Marker block, not a valid SRR file'; + return false; + } + + // Block type: STORED FILE + } elseif ($block['head_type'] == self::SRR_STORED_FILE) { + $block += self::unpack('vname_size', $this->read(2), false); + $block['file_name'] = $this->read($block['name_size']); + $block['file_data'] = $this->read((isset($block['add_size']) ? $block['add_size'] : 0)); + + // Block type: OSO HASH + } elseif ($block['head_type'] == self::SRR_OSO_HASH) { + $block += self::unpack(self::FORMAT_SRR_OSO_HASH, $this->read(18)); + $block['file_hash'] = strrev($block['file_hash']); + $block['file_size'] = self::int64($block['file_size'], $block['file_size_high']); + $block['file_name'] = $this->read($block['name_size']); + + // Block type: SRR RAR FILE + } elseif ($block['head_type'] == self::SRR_RAR_FILE) { + $block += self::unpack('vname_size', $this->read(2), false); + $block['file_name'] = $this->read($block['name_size']); + + // Default to RAR block processing + } else { + parent::processBlock($block); + } + + // Add current block to the list + $this->blocks[] = $block; + + // Skip to the next block, if any + if ($this->offset != $block['next_offset']) { + $this->seek($block['next_offset']); + } + + // Sanity check + if ($block['offset'] == $this->offset) { + $this->error = 'Parsing seems to be stuck'; + $this->close(); + return false; + } + + // No more readable data, or read error + } catch (Exception $e) { + if ($this->error) {$this->close(); return false;} + break; + } + + // Analysis was successful + return true; + } + + /** + * Resets the instance variables before parsing new data. + * + * @return void + */ + protected function reset() + { + parent::reset(); + $this->client = ''; + } + +} // End SrrInfo class diff --git a/lib/copy_this/libs/rarinfo/szipinfo.php b/lib/copy_this/libs/rarinfo/szipinfo.php new file mode 100644 index 000000000..bd8834f93 --- /dev/null +++ b/lib/copy_this/libs/rarinfo/szipinfo.php @@ -0,0 +1,1509 @@ + 'Start', + self::PROPERTY_HEADER => 'Header', + self::PROPERTY_ADDITIONAL_STREAMS_INFO => 'Additional Streams Info', + self::PROPERTY_MAIN_STREAMS_INFO => 'Main Streams Info', + self::PROPERTY_FILES_INFO => 'Files Info', + self::PROPERTY_ENCODED_HEADER => 'Encoded Header', + self::PROPERTY_END => 'End', + ); + + /** + * Are the archive headers encrypted? + * @var boolean + */ + public $isEncrypted = false; + + /** + * Is the archive packed as a solid stream? + * @var boolean + */ + public $isSolid = false; + + /** + * The number of packed streams in the archive. + * @var integer + */ + public $blockCount = 0; + + /** + * Convenience method that outputs a summary list of the file/data information, + * useful for pretty-printing. + * + * @param boolean $full add file list to output? + * @param boolean $skipDirs should directory entries be skipped? + * @return array file/data summary + */ + public function getSummary($full=false, $skipDirs=false) + { + $summary = array( + 'file_name' => $this->file, + 'file_size' => $this->fileSize, + 'data_size' => $this->dataSize, + 'use_range' => "{$this->start}-{$this->end}", + 'solid_pack' => (int) $this->isSolid, + 'enc_header' => (int) $this->hasEncodedHeader, + 'is_encrypted' => (int) $this->isEncrypted, + 'num_blocks' => $this->blockCount, + ); + $fileList = $this->getFileList($skipDirs); + $summary['file_count'] = count($fileList); + if ($full) { + $summary['file_list'] = $fileList; + } + if ($this->error) { + $summary['error'] = $this->error; + } + + return $summary; + } + + /** + * Returns a list of the 7z headers found in the file/data in human-readable + * format (for debugging purposes only). + * + * @return array|boolean list of stored headers, or false if none available + */ + public function getHeaders() + { + if (empty($this->headers)) {return false;} + $ret = array(); + + foreach ($this->headers as $header) { + $h = array(); + $h['type_name'] = isset($this->headerNames[$header['type']]) + ? $this->headerNames[$header['type']] : 'Unknown'; + $h += $header; + $ret[] = $h; + } + + return $ret; + } + + /** + * Parses the stored headers and returns a list of records for each of the + * files in the archive. + * + * @param boolean $skipDirs should directory entries be skipped? + * @return array list of file records, empty if none are available + */ + public function getFileList($skipDirs=false) + { + // Check that headers are stored + if (!($info = $this->getFilesHeaderInfo()) || empty($info['files'])) + return array(); + + // Files may be stored in their own folders or as substreams + $streams = $this->getMainStreamsInfo(); + if (!empty($streams['substreams']['unpack_sizes'])) { + $unpackSizes = $streams['substreams']['unpack_sizes']; + } elseif (!empty($streams['folders'])) { + foreach ($streams['folders'] as $folder) { + $unpackSizes[] = $this->getFolderUnpackSize($folder); + } + } + $packRanges = $this->getPackedRanges(); + $ret = array(); + + // Collate the file & streams info + $folderIndex = $sizeIndex = $streamIndex = 0; + foreach ($info['files'] as $file) { + $item = array( + 'name' => substr($file['file_name'], 0, $this->maxFilenameLength), + 'size' => ($file['has_stream'] && isset($unpackSizes[$sizeIndex])) ? $unpackSizes[$sizeIndex] : 0, + 'date' => isset($file['utime']) ? $file['utime'] : 0, + 'pass' => 0, + 'compressed' => 0, + ); + if (!empty($file['is_dir'])) { + if ($skipDirs) {continue;} + $item['is_dir'] = 1; + } + if ($file['has_stream']) { + $numStreamsInFolder = 1; + if (!empty($streams['folders'][$folderIndex])) { + $folder = $streams['folders'][$folderIndex]; + $item['pass'] = $folder['is_encrypted']; + $item['compressed'] = $folder['is_compressed']; + $item['block'] = $folderIndex; + if (isset($streams['substreams']['num_unpack_streams'][$folderIndex])) { + $numStreamsInFolder = $streams['substreams']['num_unpack_streams'][$folderIndex]; + } + } + if ($packRanges[$folderIndex] != null) { + $item['range'] = $packRanges[$folderIndex]; + } + if (!empty($streams['substreams']['digests_defined'][$sizeIndex])) { + $item['crc32'] = dechex($streams['substreams']['digests'][$sizeIndex]); + } + if (++$streamIndex == $numStreamsInFolder) { + $streamIndex = 0; + $folderIndex++; + } + $sizeIndex++; + } + $ret[] = $item; + } + + return $ret; + } + + /** + * Retrieves the raw data for the given filename. Note that this is only useful + * if the file hasn't been compressed or encrypted. + * + * @param string $filename name of the file to retrieve + * @return mixed file data, or false if no file info available + */ + public function getFileData($filename) + { + // Check that headers are stored and data source is available + if (empty($this->headers) || ($this->data == '' && $this->handle == null)) { + return false; + } + + // Get the absolute start/end positions + if (!($info = $this->getFileInfo($filename)) || empty($info['range'])) { + $this->error = "Could not find file info for: ({$filename})"; + return false; + } + $this->error = ''; + + return $this->getRange(explode('-', $info['range'])); + } + + /** + * Saves the raw data for the given filename to the given destination. Note + * that this is only useful if the file isn't compressed or encrypted. + * + * @param string $filename name of the file to extract + * @param string $destination full path of the file to create + * @return integer|boolean number of bytes saved or false on error + */ + public function saveFileData($filename, $destination) + { + // Check that headers are stored and data source is available + if (empty($this->headers) || ($this->data == '' && $this->handle == null)) { + return false; + } + + // Get the absolute start/end positions + if (!($info = $this->getFileInfo($filename)) || empty($info['range'])) { + $this->error = "Could not find file info for: ({$filename})"; + return false; + } + $this->error = ''; + + return $this->saveRange(explode('-', $info['range']), $destination); + } + + /** + * Sets the archive password for decoding encypted headers. + * + * @param string $password the password + * @return void + */ + public function setPassword($password) + { + $this->password = $password; + } + + /** + * Sets the absolute path to the external 7za client. + * + * @param string $client path to the client + * @return void + * @throws InvalidArgumentException + */ + public function setExternalClient($client) + { + if ($client && (!is_file($client) || !is_executable($client))) + throw new InvalidArgumentException("Not a valid client: {$client}"); + + $this->externalClient = $client; + } + + /** + * Extracts a compressed or encrypted file using the configured external 7za + * client, optionally returning the data or saving it to file. + * + * @param string $filename name of the file to extract + * @param string $destination full path of the file to create + * @param string $password password to use for decryption + * @return mixed extracted data, number of bytes saved or false on error + */ + public function extractFile($filename, $destination=null, $password=null) + { + if (!$this->externalClient || (!$this->file && !$this->data)) { + $this->error = 'An external client and valid data source are needed'; + return false; + } + + // Check that the file is extractable + if (!($info = $this->getFileInfo($filename))) { + $this->error = "Could not find file info for: ({$filename})"; + return false; + } + if (!empty($info['pass']) && $password == null) { + $this->error = "The file is passworded: ({$filename})"; + return false; + } + + // Set the data file source + $source = $this->file ? $this->file : $this->createTempDataFile(); + + // Set the external command + $pass = $password ? '-p'.escapeshellarg($password) : ''; + $command = '"'.$this->externalClient.'"' + ." e -so -bd -y -t7z {$pass} -- " + .escapeshellarg($source).' '.escapeshellarg($filename); + + // Set STDERR to write to a temporary file + list($hash, $errorFile) = $this->getTempFileName($source.'errors'); + $this->tempFiles[$hash] = $errorFile; + $command .= ' 2> '.escapeshellarg($errorFile); + + // Start the new pipe reader + $pipe = new PipeReader; + if (!$pipe->open($command)) { + $this->error = $pipe->error; + return false; + } + $this->error = ''; + + // Open destination file or start buffer + if ($destination) { + $handle = fopen($destination, 'wb'); + $written = 0; + } else { + $data = ''; + } + // Buffer the piped data or save it to file + while ($read = $pipe->read(1024, false)) { + if ($destination) { + $written += fwrite($handle, $read); + } else { + $data .= $read; + } + } + if ($destination) {fclose($handle);} + $pipe->close(); + + // Check for errors (only after the pipe is closed) + if (($error = @file_get_contents($errorFile)) && strpos($error, 'Everything is Ok') === false) { + if ($destination) {@unlink($destination);} + $this->error = $error; + return false; + } + + return $destination ? $written : $data; + } + + /** + * Returns the position of the starting header signature in the file/data. + * + * @return mixed start position, or false if no valid signature found + */ + public function findMarker() + { + if ($this->markerPosition !== null) + return $this->markerPosition; + + try { + $buff = $this->read(min($this->length, $this->maxReadBytes)); + $this->rewind(); + return $this->markerPosition = strpos($buff, self::MARKER_SIGNATURE); + } catch (Exception $e) { + return false; + } + } + + /** + * List of headers found in the file/data. + * @var array + */ + protected $headers = array(); + + /** + * Are the archive headers encoded? + * @var boolean + */ + protected $hasEncodedHeader = false; + + /** + * The archive password for decoding encrypted headers. + * @var string + */ + protected $password = ''; + + /** + * Full path to the external 7za client. + * @var string + */ + protected $externalClient = ''; + + /** + * Parses the 7z data and stores a list of valid headers locally. + * + * @return boolean false if parsing fails + */ + protected function analyze() + { + // Find the marker signature, if there is one + $startPos = $this->findMarker(); + if ($startPos === false && !$this->isFragment) { + + // Not a 7z fragment or valid file, so abort here + $this->error = 'Could not find marker signature, not a valid 7z file'; + return false; + + } elseif ($startPos !== false) { + + // Unpack the Start header + $this->seek($startPos + strlen(self::MARKER_SIGNATURE)); + $header = $this->readStartHeader(); + $this->headers[] = $header; + + // Go to the next header if available + $this->seek(min($header['next_offset'], $this->length)); + + } elseif ($this->isFragment) { + + // Search for a valid header and continue unpacking from there + if (($startPos = $this->findHeader()) === false) { + $this->error = 'Could not find a valid 7z header'; + return false; + } + $this->seek($startPos); + } + + // Analyze all headers + while ($this->offset < $this->length) try { + + // Get the next header + if (($header = $this->readNextHeader()) === false) + break; + + // Add the current header to the list + $this->headers[] = $header; + + // Skip to the next header, if any + if ($this->offset != $header['next_offset']) { + $this->seek($header['next_offset']); + } + + // Sanity check + if ($header['offset'] == $this->offset) { + $this->error = 'Parsing seems to be stuck'; + $this->close(); + return false; + } + + // No more readable data, or read error + } catch (Exception $e) { + if ($this->error) {$this->close(); return false;} + break; + } + + // Check for valid headers + if (empty($this->headers)) { + $this->error = 'No valid 7z headers were found'; + return false; + } + + // Analysis was successful + if ($this->hasEncodedHeader && $this->externalClient) { + return $this->extractHeaders(); + } + return true; + } + + /** + * Searches for the position of a valid header up to maxReadBytes, and sets + * it as the start of the data to analyze. + * + * @return integer|boolean the header offset, or false if none is found + */ + protected function findHeader() + { + // Buffer the data to search + $start = $this->offset; + try { + $buffer = $this->read(min($this->length, $this->maxReadBytes)); + $this->rewind(); + } catch (Exception $e) {return false;} + + // Get all the offsets to test + $searches = array( + 'unencoded' => pack('C*', self::PROPERTY_HEADER, self::PROPERTY_MAIN_STREAMS_INFO), + 'encoded' => pack('C*', self::PROPERTY_ENCODED_HEADER, self::PROPERTY_PACK_INFO), + ); + if (!($positions = self::strposall($buffer, $searches))) + return false; + + foreach ($positions as $offset => $matches) try { + $offset += $start; + $this->seek(($matches[0] == 'encoded') ? $offset : $offset + 1); + + // Verify the Header or Encoded Header data + if (($header = $this->readNextHeader()) && $this->sanityCheckStreamsInfo($header)) { + return $this->markerPosition = $offset; + } + + // No more readable data, or read error + } catch (Exception $e) {continue;} + + return false; + } + + /** + * Unpacks the Start header info from the current offset. + * + * @return array|boolean the Start header info, or false on error + */ + protected function readStartHeader() + { + $header = array( + 'offset' => $this->offset, + 'type' => self::START_HEADER, + ); + try { + $header += self::unpack(self::START_HEADER_FORMAT, $this->read(self::START_HEADER_SIZE)); + } catch (Exception $e) { + return false; + } + $header['next_head_offset'] = self::int64($header['next_head_offset'], $header['next_head_offset_high']); + $header['next_head_size'] = self::int64($header['next_head_size'], $header['next_head_size_high']); + $header['next_offset'] = $this->offset + $header['next_head_offset']; + $header['data_offset'] = $this->offset; + + return $header; + } + + /** + * Reads the start of the next header before further processing by type. + * + * @return array|boolean the next header info, or false on error + */ + protected function readNextHeader() + { + $header = array( + 'offset' => $this->offset, + 'type' => ord($this->read(1)), + 'next_offset' => $this->length, + ); + switch ($header['type']) { + + // Start/end header markers + case self::PROPERTY_HEADER: + case self::PROPERTY_END: + $header['next_offset'] = $header['offset'] + 1; + return $header; + + case self::PROPERTY_ARCHIVE_PROPERTIES: + return $this->processArchiveProperties($header); + + case self::PROPERTY_ADDITIONAL_STREAMS_INFO: + case self::PROPERTY_MAIN_STREAMS_INFO: + case self::PROPERTY_ENCODED_HEADER: + return $this->processStreamsInfo($header); + + case self::PROPERTY_FILES_INFO: + return $this->processFilesInfo($header); + + // Unknown types + default: + return $header; + } + } + + /** + * Reads & parses info about various archive streams from the current offset, + * and adds it to the given header record. + * + * @param array $header a valid header record + * @return boolean false on error + */ + protected function processStreamsInfo(&$header) + { + $nid = ord($this->read(1)); + + // Pack Info + if ($nid == self::PROPERTY_PACK_INFO) { + if (!$this->processPackInfo($header)) + return false; + $this->isSolid = (bool) $header['is_solid']; + $nid = ord($this->read(1)); + } + + // Unpack Info + if ($nid == self::PROPERTY_UNPACK_INFO) { + if (!$this->processUnpackInfo($header)) + return false; + $this->blockCount = $header['num_folders']; + $nid = ord($this->read(1)); + } + + // Substreams Info + if ($nid == self::PROPERTY_SUBSTREAMS_INFO) { + if (!$this->processSubstreamsInfo($header)) + return false; + $nid = ord($this->read(1)); + } + + // End Streams Info + if (!$this->checkIsEnd($nid)) {return false;} + $this->hasEncodedHeader = ($header['type'] == self::PROPERTY_ENCODED_HEADER); + $header['next_offset'] = $this->offset; + + return $header; + } + + /** + * Reads & parses basic info about the packed streams in the archive. + * + * @param array $header a valid header record + * @return boolean false on error + */ + protected function processPackInfo(&$header) + { + $header['pack_offset'] = $this->readNumber(); + $header['num_streams'] = $this->readNumber(); + $header['is_solid'] = (int) ($header['num_streams'] == 1); + $nid = ord($this->read(1)); + + // Packed sizes + if ($nid == self::PROPERTY_SIZE) { + $header['pack_sizes'] = array(); + for ($i = 0; $i < $header['num_streams']; $i++) { + $header['pack_sizes'][$i] = $this->readNumber(); + } + $nid = ord($this->read(1)); + + // Packed CRC digests + if ($nid == self::PROPERTY_CRC) { + $digests = $this->readDigests($header['num_streams']); + $header['pack_digests_defined'] = array(); + $header['pack_crcs'] = array(); + for ($i = 0; $i < $header['num_streams']; $i++) { + $header['pack_digests_defined'][$i] = $digests['defined'][$i]; + $header['pack_crcs'][$i] = $digests['crcs'][$i]; + } + $nid = ord($this->read(1)); + } + } + + return $this->checkIsEnd($nid); + } + + /** + * Reads & parses further info about the contents of the packed streams. + * + * @param array $header a valid header record + * @return boolean false on error + */ + protected function processUnpackInfo(&$header) + { + $nid = ord($this->read(1)); + + // Folders (packed stream blocks) + if ($nid != self::PROPERTY_FOLDER) { + $this->error = "Expecting PROPERTY_FOLDER but found: {$nid} at: ".($this->offset - 1); + return false; + } + $header['num_folders'] = $this->readNumber(); + if (!$this->checkExternal()) {return false;} + $this->processFolders($header); + $nid = ord($this->read(1)); + + // Unpack sizes + if ($nid != self::PROPERTY_CODERS_UNPACK_SIZE) { + $this->error = "Expecting PROPERTY_CODERS_UNPACK_SIZE but found: {$nid} at: ".($this->offset - 1); + return false; + } + foreach ($header['folders'] as &$folder) { + $folder['unpack_sizes'] = array(); + for ($i = 0; $i < $folder['total_out_streams']; $i++) { + $folder['unpack_sizes'][] = $this->readNumber(); + } + } + $nid = ord($this->read(1)); + + // Unpack digests + if ($nid == self::PROPERTY_CRC) { + $digests = $this->readDigests($header['num_folders']); + for ($i = 0; $i < $header['num_folders']; $i++) { + $header['folders'][$i]['digest_defined'] = $digests['defined'][$i]; + $header['folders'][$i]['unpack_crc'] = $digests['crcs'][$i]; + } + $nid = ord($this->read(1)); + } + + return $this->checkIsEnd($nid); + } + + /** + * Reads & parses info about the packed 'folders' or stream blocks. These + * may combine data from multiple files as substreams to improve compression, + * and may each use multiple (chained) encoding methods. + * + * @param array $header a valid header record + * @return void + */ + protected function processFolders(&$header) + { + $header['folders'] = array(); + + for ($f = 0; $f < $header['num_folders']; $f++) { + $folder = array( + 'is_encrypted' => 0, + 'is_compressed' => 0, + 'num_coders' => $this->readNumber(), + ); + $totalInStreams = $totalOutStreams = 0; + + // Coders info + $folder['coders'] = array(); + for ($c = 0; $c < $folder['num_coders']; $c++) { + $coder = array(); + $coder['flags'] = ord($this->read(1)); + $codecSize = $coder['flags'] & 0x0f; + $isComplex = $coder['flags'] & 0x10; + $hasProps = $coder['flags'] & 0x20; + + // In/out streams + $coder += self::unpack('H*method', $this->read($codecSize)); + $coder['num_in_streams'] = $isComplex ? $this->readNumber() : 1; + $coder['num_out_streams'] = $isComplex ? $this->readNumber() : 1; + $totalInStreams += $coder['num_in_streams']; + $totalOutStreams += $coder['num_out_streams']; + + // Properties + if ($hasProps) { + $propSize = $this->readNumber(); + $coder['prop_size'] = $propSize; + $coder += self::unpack('H*properties', $this->read($propSize)); + } + $folder['coders'][] = $coder; + + // Encryption & compression + if ($coder['method'] == self::METHOD_7Z_AES) { + $folder['is_encrypted'] = 1; + if ($header['type'] == self::PROPERTY_ENCODED_HEADER) { + $this->isEncrypted = true; + } + } elseif ($coder['method'] != self::METHOD_COPY) { + $folder['is_compressed'] = 1; + } + } + $folder['total_out_streams'] = $totalOutStreams; + $folder['total_in_streams'] = $totalInStreams; + + // Bind pairs + $folder['num_bind_pairs'] = $numBindPairs = $totalOutStreams - 1; + $bindPairs = array(); + if ($numBindPairs > 0) { + for ($p = 0; $p < $numBindPairs; $p++) { + $bindPairs[] = array( + 'in' => $this->readNumber(), + 'out' => $this->readNumber(), + ); + } + $folder['bind_pairs'] = $bindPairs; + } + + // Packed indexes + $folder['num_packed_streams'] = $numPackedStreams = $totalInStreams - $numBindPairs; + $packedIndexes = array(); + if ($numPackedStreams == 1) { + for ($i = 0; $i < $totalInStreams; $i++) { + if ($this->findBindPair($bindPairs, $i, 'in') < 1) { + $packedIndexes[] = $i; + } + } + } elseif ($numPackedStreams > 1) { + for ($i = 0; $i < $numPackedStreams; $i++) { + $packedIndexes[] = $this->readNumber(); + } + } + $folder['packed_indexes'] = $packedIndexes; + $header['folders'][] = $folder; + } + } + + /** + * Reads & parses info about the substreams in each packed 'folder'. + * + * @param array $header a valid header record + * @return boolean false on error + */ + protected function processSubstreamsInfo(&$header) + { + if (empty($header['folders'])) { + $this->error = 'No folders found, cannot process substreams info'; + return false; + } + $nid = ord($this->read(1)); + $subs = array(); + + // Number of unpack streams in each folder + if ($nid == self::PROPERTY_NUM_UNPACK_STREAM) { + $subs['num_unpack_streams'] = array(); + for ($i = 0; $i < $header['num_folders']; $i++) { + $subs['num_unpack_streams'][] = $this->readNumber(); + } + $nid = ord($this->read(1)); + } else { + $subs['num_unpack_streams'] = array_fill(0, $header['num_folders'], 1); + } + + // Substream unpack sizes + if ($nid == self::PROPERTY_SIZE) { + $subs['unpack_sizes'] = array(); + for ($i = 0; $i < $header['num_folders']; $i++) { + $sum = 0; + if (($numStreams = $subs['num_unpack_streams'][$i]) == 0) + continue; + for ($j = 1; $j < $numStreams; $j++) { + $size = $this->readNumber(); + $subs['unpack_sizes'][] = $size; + $sum += $size; + } + $subs['unpack_sizes'][] = $this->getFolderUnpackSize($header['folders'][$i]) - $sum; + } + $nid = ord($this->read(1)); + } + + // Substream unpack digests (for streams with unknown CRC) + $numDigests = $numDigestsTotal = 0; + for ($i = 0; $i < $header['num_folders']; $i++) { + $numStreams = $subs['num_unpack_streams'][$i]; + if ($numStreams != 1 || empty($header['folders'][$i]['digest_defined'])) { + $numDigests += $numStreams; + } + $numDigestsTotal += $numStreams; + } + if ($nid == self::PROPERTY_CRC) { + $subs['digests_defined'] = array(); + $subs['digests'] = array(); + $digests = $this->readDigests($numDigests); + $digestIndex = 0; + for ($i = 0; $i < $header['num_folders']; $i++) { + $numStreams = $subs['num_unpack_streams'][$i]; + if ($numStreams == 1 && !empty($header['folders'][$i]['digest_defined'])) { + $subs['digests_defined'][] = 1; + $subs['digests'][] = $header['folders'][$i]['unpack_crc']; + } else { + for ($j = 0; $j < $numStreams; $j++, $digestIndex++) { + $subs['digests_defined'][] = $digests['defined'][$digestIndex]; + $subs['digests'][] = $digests['crcs'][$digestIndex]; + } + } + } + $nid = ord($this->read(1)); + } else { + $subs['digests_defined'] = array_fill(0, $numDigestsTotal, 0); + $subs['digests'] = array_fill(0, $numDigestsTotal, 0); + } + + $header['substreams'] = $subs; + return $this->checkIsEnd($nid); + } + + /** + * Reads & parses information about the files stored in the archive. + * + * @param array $header a valid header record + * @return boolean false on error + */ + protected function processFilesInfo(&$header) + { + // Start the file list + $header['num_files'] = $this->fileCount = $this->readNumber(); + $header['files'] = array(); + for ($i = 0; $i < $header['num_files']; $i++) { + $header['files'][$i]['has_stream'] = 1; + } + $numEmptyStreams = 0; + + // Read the file info properties + while ($this->offset < $this->length) { + + // Property type & size + $type = $this->readNumber(); + if ($type > 255) { + $this->error = "Invalid type, must be below 256: {$type} at: ".($this->offset - 1); + return false; + } elseif ($type == self::PROPERTY_END) { + break; + } + $size = $this->readNumber(); + + // File names + if ($type == self::PROPERTY_NAME) { + if (!$this->checkExternal()) {return false;} + foreach ($header['files'] as &$file) { + $name = ''; + while ($this->offset < $this->length) { + $data = $this->read(2); + if ($data == "\x00\x00") { + $file['file_name'] = @iconv('UTF-16LE', 'UTF-8//IGNORE//TRANSLIT', $name); + break; + } + $name .= $data; + } + } + } + + // File times + elseif ($type == self::PROPERTY_LAST_WRITE_TIME) { + $this->processFileTimes($header, 'mtime'); + } + elseif ($type == self::PROPERTY_CREATION_TIME) { + $this->processFileTimes($header, 'ctime'); + } + elseif ($type == self::PROPERTY_LAST_ACCESS_TIME) { + $this->processFileTimes($header, 'atime'); + } + + // File attributes + elseif ($type == self::PROPERTY_ATTRIBUTES) { + $defined = $this->readBooleans($header['num_files'], true); + if (!$this->checkExternal()) {return false;} + foreach ($header['files'] as $i => &$file) { + if ($defined[$i] == 1) { + $file += self::unpack('Vattributes', $this->read(4)); + } else { + $file['attributes'] = null; + } + } + } + + // Start positions + elseif ($type == self::PROPERTY_START_POSITION) { + $defined = $this->readBooleans($header['num_files'], true); + if (!$this->checkExternal()) {return false;} + foreach ($header['files'] as $i => &$file) { + if ($defined[$i] == 1) { + $sp = self::unpack('Vlow/Vhigh', $this->read(8)); + $file['start_pos'] = self::int64($sp['low'], $sp['high']); + } else { + $file['start_pos'] = null; + } + } + } + + // Empty streams/files flags + elseif ($type == self::PROPERTY_EMPTY_STREAM) { + $header['empty_streams'] = $this->readBooleans($header['num_files']); + $numEmptyStreams = array_sum($header['empty_streams']); + } + elseif ($type == self::PROPERTY_EMPTY_FILE) { + $header['empty_files'] = $this->readBooleans($numEmptyStreams); + } + elseif ($type == self::PROPERTY_ANTI) { + $header['anti_files'] = $this->readBooleans($numEmptyStreams); + } + + // Skip unknowns + else {$this->read($size);} + } + + // Process empty streams/files + $emptyFileIndex = 0; + foreach ($header['files'] as $i => &$file) { + if (!empty($header['empty_streams'][$i])) { + $file['has_stream'] = 0; + if (empty($header['empty_files'][$emptyFileIndex])) { + $file['is_dir'] = 1; + } + if (!empty($header['anti_files'][$emptyFileIndex])) { + $file['is_anti'] = 1; + } + $emptyFileIndex++; + } + } + + // End Files Info + $header['next_offset'] = $this->offset; + return $header; + } + + /** + * Reads & parses info about the given file time properties. + * + * @param array $header a valid header record + * @param string $type the file time type + * @return boolean false on error + */ + protected function processFileTimes(&$header, $type) + { + $defined = $this->readBooleans($header['num_files'], true); + if (!$this->checkExternal()) {return false;} + + foreach ($header['files'] as $i => &$file) { + if ($defined[$i] == 1) { + $time = self::unpack('Vlow/Vhigh', $this->read(8)); + $file[$type] = $time; + if ($type == 'mtime') { + $utime = self::win2unixtime($time['low'], $time['high']); + $file['utime'] = $utime; + } + } else { + $file[$type] = null; + } + } + } + + /** + * This doesn't seem to be implemented by any client, not even in the reference + * C++ code for the 7-zip client. + * + * @param array $header a valid header record + * @return boolean false on error + */ + protected function processArchiveProperties(&$header) + { + $this->error = 'Archive properties not implemented, at: '.$this->offset; + return false; + } + + /** + * Determines whether the given property ID byte is an end ID, otherwise sets + * an error for the related offset. + * + * @param string $nid the property ID + * @return boolean false on error + */ + protected function checkIsEnd($nid) + { + if ($nid != self::PROPERTY_END) { + $this->error = "Expecting PROPERTY_END but found: {$nid} at: ".($this->offset - 1); + return false; + } + return true; + } + + /** + * Determines whether an external switch has been set at the current offset + * and sets an error if it has, since the feature isn't supported. + * + * @return boolean false if the external switch is set + */ + protected function checkExternal() + { + $external = ord($this->read(1)); + if ($external != 0) { + $this->error = "External switch not implemented, at: ".($this->offset - 1); + return false; + } + return true; + } + + /** + * Tests whether the given header is a valid streams info header. + * + * @param array $header the header to sanity check + * @param integer $limit the minimum failure threshold + * @return boolean false if the sanity check fails + */ + protected function sanityCheckStreamsInfo($header, $limit=3) + { + $fail = (!isset($header['pack_offset']) || $header['pack_offset'] > PHP_INT_MAX) + + (empty($header['pack_sizes']) || $header['pack_sizes'][0] > PHP_INT_MAX) + + (empty($header['num_folders']) || $header['num_folders'] > 50) + + (empty($header['num_streams']) || $header['num_streams'] > 50) + + (empty($header['folders']) || empty($header['folders']['coders'])); + + return $fail < $limit; + } + + /** + * Reads a variable length integer value from the current offset, which may be + * an unsigned integer or float depending on the size and system. + * + * The first byte in the little-endian sequence contains the continuation bit + * flags, where 1 = read a new byte and add it to the value, and any remaining + * bits after 0 are the high bits of the value. The maximum value is an unsigned + * 64-bit integer in a 9-byte sequence. + * + * @return integer|float the variable length value, or zero on under/overflow + */ + protected function readNumber() + { + $first = ord($this->read(1)); + $low = $high = 0; + $mask = 0x80; + + for ($count = 0; $count < 8; $count++) { + if (($first & $mask) == 0) { + $remainder = ($first & ($mask - 1)); + if ($count < 4) { + $low += $remainder << ($count * 8); + } else { + $high += $remainder << (($count - 4) * 8); + } + if ($low < 0) {$low += 0x100000000;} + if ($high < 0) {$high += 0x100000000;} + return ($high ? self::int64($low, $high) : $low); + } + $next = ord($this->read(1)); + if ($count < 4) { + $low += $next << ($count * 8); + } else { + $high += $next << (($count - 4) * 8); + } + $mask >>= 1; + } + + return 0; + } + + /** + * Reads a list of boolean bit flags from the current offset. + * + * @param integer $count the number of booleans to read + * @param integer $checkAll read an all defined flag first? + * @return array the list of boolean flags + */ + protected function readBooleans($count, $checkAll=false) + { + if ($checkAll) { + $allDefined = ord($this->read(1)); + if ($allDefined != 0) { + return array_fill(0, $count, 1); + } + } + $result = array(); + $byte = $mask = 0; + for ($i = 0; $i < $count; $i++) { + if ($mask == 0) { + $byte = ord($this->read(1)); + $mask = 0x80; + } + $result[$i] = (int) (($byte & $mask) != 0); + $mask >>= 1; + } + + return $result; + } + + /** + * Reads a list of CRC digests from the current offset. + * + * @param integer $count the number of digests to read + * @return array the digests info + */ + protected function readDigests($count) + { + $digests = array( + 'defined' => $this->readBooleans($count, true), + 'crcs' => array(), + ); + for ($i = 0; $i < $count; $i++) { + if (!empty($digests['defined'][$i])) { + $crc = self::unpack('V', $this->read(4)); + $digests['crcs'][$i] = $crc[1]; + } else { + $digests['crcs'][$i] = 0; + } + } + + return $digests; + } + + /** + * Searches for a bind pair that corresponds with the given stream index. + * + * @param array $pairs the bind pair list + * @param integer $index the stream index to search + * @param string $type the type of bind pair ('in' or 'out') + * @return integer the bind pair index, or -1 if none found + */ + protected function findBindPair($pairs, $index, $type) + { + foreach ($pairs as $idx => $pair) { + if ($pair[$type] == $index) + return $idx; + } + return -1; + } + + /** + * Calculates the final unpack size for the given packed 'folder'. + * + * @param array $folder a valid folder record + * @return integer the final unpack size in bytes + */ + protected function getFolderUnpackSize($folder) + { + if (empty($folder['unpack_sizes'])) + return 0; + + $pairs = isset($folder['bind_pairs']) ? $folder['bind_pairs'] : array(); + for ($i = count($folder['unpack_sizes']) - 1; $i >= 0; $i--) { + if ($this->findBindPair($pairs, $i, 'out') < 0) { + return $folder['unpack_sizes'][$i]; + } + } + return 0; + } + + /** + * Calculates the absolute start and end positions for each of the packed + * blocks in the current file/data, including for sources with partial data, + * i.e. fragments or any split archive volumes. The range is set to null only + * if the packed data for the block is completely missing. + * + * @return array the list of absolute ranges + */ + protected function getPackedRanges() + { + if (!($mainStreams = $this->getMainStreamsInfo())) + return false; + + $startHeader = $this->getStartHeader(); + $mainHeader = $this->getMainHeader(); + $encodedHeader = $this->getEncodedHeader(); + $packSizes = $mainStreams['pack_sizes']; + + if ($startHeader) { + $start = $this->start + $startHeader['data_offset']; + $end = $start + array_sum($packSizes) - 1; + } else { + $start = $this->start; + if ($encodedHeader) { + $end = $start + $encodedHeader['offset'] - $encodedHeader['pack_sizes'][0] - 1; + } else { + $end = $start + $mainHeader['offset'] - 1; + } + } + + $ranges = array(); + $blockEnd = $end; + foreach (array_reverse($packSizes) as $size) { + if ($blockEnd < $start) { + $ranges[] = null; + continue; + } + $blockStart = max($start, $blockEnd - $size + 1); + $ranges[] = "{$blockStart}-{$blockEnd}"; + $blockEnd -= $size; + } + + return array_reverse($ranges); + } + + /** + * Retrieves the stored Main Streams Info header. + * + * @return array|boolean the header info, or false if none available + */ + protected function getMainStreamsInfo() + { + foreach ($this->headers as $header) { + if ($header['type'] == self::PROPERTY_MAIN_STREAMS_INFO) + return $header; + } + return false; + } + + /** + * Retrieves the stored Encoded Header info. + * + * @return array|boolean the header info, or false if none available + */ + protected function getEncodedHeader() + { + foreach ($this->headers as $header) { + if ($header['type'] == self::PROPERTY_ENCODED_HEADER) + return $header; + } + return false; + } + + /** + * Retrieves the stored main (unencoded) Header info. + * + * @return array|boolean the header info, or false if none available + */ + protected function getMainHeader() + { + foreach ($this->headers as $header) { + if ($header['type'] == self::PROPERTY_HEADER) + return $header; + } + return false; + } + + /** + * Retrieves the stored Start header info. + * + * @return array|boolean the header info, or false if none available + */ + protected function getStartHeader() + { + foreach ($this->headers as $header) { + if ($header['type'] == self::START_HEADER) + return $header; + } + return false; + } + + /** + * Retrieves the stored Files Info header. + * + * @return array|boolean the header info, or false if none available + */ + protected function getFilesHeaderInfo() + { + foreach ($this->headers as $header) { + if ($header['type'] == self::PROPERTY_FILES_INFO) + return $header; + } + return false; + } + + /** + * Returns information for the given filename in the current file/data. + * + * @param string $filename the filename to search + * @return array|boolean the file info or false on error + */ + protected function getFileInfo($filename) + { + foreach ($this->getFileList(true) as $file) { + if (isset($file['name']) && $file['name'] == $filename) { + return $file; + } + } + return false; + } + + /** + * Extracts any encoded headers by creating a dummy archive with the encoded + * header data as the file, and extracting that file with an external client. + * The uncompressed/decrypted header info is then appended to the local stored + * headers list. + * + * @return boolean true if extraction was successful + */ + protected function extractHeaders() + { + if (!$this->externalClient) { + $this->error = 'A valid external client is needed to extract headers'; + return false; + } + if ($this->isEncrypted && !$this->password) { + $this->error = 'Archive headers are encrypted, password needed'; + return false; + } + if (($encoded = $this->getEncodedHeader()) === false) + return false; + + try { + // Fetch the Encoded Header packed data + $packSize = $encoded['pack_sizes'][0]; + if ($startHeader = $this->getStartHeader()) { + $this->seek($startHeader['data_offset'] + $encoded['pack_offset']); + } else { + $pos = $encoded['offset'] - $packSize; + if ($pos < 0) { + $this->error = 'Not enough data available to decode headers'; + return false; + } + $this->seek($pos); + } + $data = $this->read($packSize); + + // Header + Main Streams Info start + $head = pack('C*', self::PROPERTY_HEADER, self::PROPERTY_MAIN_STREAMS_INFO); + $this->seek($encoded['offset'] + 1); // skip Encoded Header id + $head .= $this->read(1); // Pack Info id + $this->readNumber(); // skip pack_offset + $head .= "\x00"; // make pack_offset = 0 + + // Remainder (skipping final null) + $head .= $this->read($encoded['next_offset'] - $this->offset - 1); + + } catch (Exception $e) {return false;} + + // Substreams Info (skipping digests) + $head .= pack('C*', self::PROPERTY_SUBSTREAMS_INFO, self::PROPERTY_NUM_UNPACK_STREAM, 1, 0, 0); + + // File Info (for dummy 'header.txt'); + $head .= pack('C', self::PROPERTY_FILES_INFO); + $head .= pack('H*', '011117006800650061006400650072002e00740078007400'); + $head .= pack('H*', '0000140a010059ca701f4a7ece0115060100200000000000'); + + // Start Header + $major = $startHeader ? $startHeader['version_major'] : 0; + $minor = $startHeader ? $startHeader['version_minor'] : 3; + $start = self::MARKER_SIGNATURE; // signature + $start .= pack('C*', $major, $minor); // version info + $startData = pack('V*', $packSize, 0); // next_head_offset + $startData .= pack('V*', strlen($head), 0, crc32($head)); // next_head_size, next_head_crc + $start .= pack('V', crc32($startData)); // start head_crc + $start .= $startData; // remainder + + // Save the dummy to a temporary file + list($hash, $temp) = $this->getTempFileName($data); + $this->tempFiles[$hash] = $temp; + file_put_contents($temp, $start.$data.$head); + unset($start, $data, $head); + + // Extract the header info with a new instance + $szip = new self($temp, true); + $szip->externalClient = $this->externalClient; + if (($data = $szip->extractFile('header.txt', null, $this->password)) + && $szip->setData($data, true) + ) { + $this->headers = array_merge($this->headers, $szip->getHeaders()); + $this->isSolid = $szip->isSolid; + $this->blockCount = $szip->blockCount; + $this->fileCount = $szip->fileCount; + $this->error = ''; + return true; + } + + // Failed miserably! + $this->error = $szip->error; + return false; + } + + /** + * Resets the instance variables before parsing new data. + * + * @return void + */ + protected function reset() + { + parent::reset(); + $this->headers = array(); + $this->isEncrypted = false; + $this->hasEncodedHeader = false; + $this->isSolid = false; + $this->blockCount = 0; + } + +} // End SzipInfo class diff --git a/lib/copy_this/libs/rarinfo/zipinfo.php b/lib/copy_this/libs/rarinfo/zipinfo.php new file mode 100644 index 000000000..e4b133f9a --- /dev/null +++ b/lib/copy_this/libs/rarinfo/zipinfo.php @@ -0,0 +1,790 @@ + + * + * // Load the ZIP file or data + * $zip = new ZipInfo; + * $zip->open('./foo.zip'); // or $zip->setData($data); + * if ($zip->error) { + * echo "Error: {$zip->error}\n"; + * exit; + * } + * + * // Check encryption + * if ($zip->isEncrypted) { + * echo "Archive is encrypted\n"; + * exit; + * } + * + * // Process the file list + * $files = $zip->getFileList(); + * foreach ($files as $file) { + * if ($file['pass'] == true) { + * echo "File is passworded: {$file['name']}\n"; + * } + * if ($file['compressed'] == false) { + * echo "Extracting uncompressed file: {$file['name']}\n"; + * $zip->saveFileData($file['name'], "./destination/{$file['name']}"); + * // or $data = $zip->getFileData($file['name']); + * } + * } + * + * + * + * The ZIP specification is quite bloated (particularly when it comes to extra + * fields and OS-specific info) and only a small part of it is implemented here, + * but there's lots still to explore: + * + * @link http://www.pkware.com/documents/casestudies/APPNOTE.TXT + * + * @author Hecks + * @copyright (c) 2010-2013 Hecks + * @license Modified BSD + * @version 2.1 + */ +class ZipInfo extends ArchiveReader +{ + // ------ Class constants ----------------------------------------------------- + + /**#@+ + * ZIP file format values + */ + + // Record type signatures + const RECORD_CENTRAL_FILE = 0x02014b50; + const RECORD_LOCAL_FILE = 0x04034b50; + const RECORD_SIGNATURE = 0x05054b50; + const RECORD_ENDCENTRAL = 0x06054b50; + const RECORD_Z64_ENDCENTRAL = 0x06064b50; + const RECORD_Z64_ENDCENTRAL_LOC = 0x07064b50; + const RECORD_ARCHIVE_EXTRA = 0x08064b50; + const RECORD_DATA_DESCR = 0x08074b50; + + // General purpose flags + const FILE_ENCRYPTED = 0x0001; + const FILE_DESCRIPTOR_USED = 0x0008; + const FILE_STRONG_ENCRYPTED = 0x0040; + const FILE_EFS_UTF8 = 0x0800; + const FILE_CDR_ENCRYPTED = 0x2000; + + // Extra Field IDs + const EXTRA_ZIP64 = 0x0001; + const EXTRA_NTFS = 0x000a; + const EXTRA_UNIX = 0x000d; + const EXTRA_STRONG_ENCR = 0x0017; + const EXTRA_POSZIP = 0x4690; + const EXTRA_UNIXTIME = 0x5455; + const EXTRA_IZUNIX = 0x5855; + const EXTRA_IZUNIX2 = 0x7855; + const EXTRA_IZUNIX3 = 0x7875; + const EXTRA_WZ_AES = 0x9901; + + // OS Types + const OS_FAT = 0; + const OS_AMIGA = 1; + const OS_VMS = 2; + const OS_UNIX = 3; + const OS_VM_CMS = 4; + const OS_ATARI = 5; + const OS_HPFS = 6; + const OS_MAC = 7; + const OS_Z_SYSTEM = 8; + const OS_CPM = 9; + const OS_NTFS = 10; + const OS_MVS = 11; + const OS_VSE = 12; + const OS_ACORN = 13; + const OS_VFAT = 14; + const OS_ALT_MVS = 15; + const OS_BEOS = 16; + const OS_TANDEM = 17; + const OS_OS400 = 18; + const OS_OSX = 19; + + /**#@-*/ + + /** + * Format for unpacking Local File records. + */ + const FORMAT_LOCAL_FILE = 'Cversion_need_num/Cversion_need_os/vflags/vmethod/vlast_mod_time/vlast_mod_date/Vcrc32/Vcompressed_size/Vuncompressed_size/vfile_name_length/vextra_length'; + + /** + * Format for unpacking Central File records. + */ + const FORMAT_CENTRAL_FILE = 'Cversion_made_num/Cversion_made_os/Cversion_need_num/Cversion_need_os/vflags/vmethod/vlast_mod_time/vlast_mod_date/Vcrc32/Vcompressed_size/Vuncompressed_size/vfile_name_length/vextra_length/vcomment_length/vdisk_start/vattr_int/Vattr_ext/Vrel_offset'; + + /** + * Format for unpacking End of Central Directory records. + */ + const FORMAT_ENDCENTRAL = 'vdisk_num/vstart_disk/ventries_disk/ventries_total/Vcentral_size/Vcentral_offset/vcomment_length'; + + /** + * Format for unpacking ZIP64 format End of Central Directory records. + */ + const FORMAT_Z64_ENDCENTRAL = 'Vcentral_size/Vcentral_size_high/Cversion_made_num/Cversion_made_os/Cversion_need_num/Cversion_need_os/Vdisk_num/Vstart_disk/Ventries_disk/Ventries_disk_high/Ventries_total/Ventries_total_high/Vcentral_offset/Vcentral_offset_high'; + + /** + * Format for unpacking ZIP64 format End of Central Directory Locator records. + */ + const FORMAT_Z64_ENDCENTRAL_LOC = 'Vstart_disk/Vcentral_offset/Vcentral_offset_high/Vtotal_disks'; + + /** + * Format for unpacking Data Descriptor blocks. + */ + const FORMAT_DATA_DESCR = 'Vsignature/Vcrc32/Vcompressed_size/Vuncompressed_size'; + + /** + * Format for unpacking Extra Field blocks. + */ + const FORMAT_EXTRA_FIELD = 'vheaderID/vdata_size'; + + + // ------ Instance variables and methods --------------------------------------- + + /** + * List of record names corresponding to record types. + * @var array + */ + protected $recordNames = array( + self::RECORD_CENTRAL_FILE => 'Central File', + self::RECORD_LOCAL_FILE => 'Local File', + self::RECORD_SIGNATURE => 'Digital Signature', + self::RECORD_ENDCENTRAL => 'End of Central Directory', + self::RECORD_Z64_ENDCENTRAL => 'ZIP64 End of Central Directory', + self::RECORD_Z64_ENDCENTRAL_LOC => 'ZIP64 End of Central Directory Locator', + self::RECORD_ARCHIVE_EXTRA => 'Archive Extra Data', + self::RECORD_DATA_DESCR => 'Data Descriptor', + ); + + /** + * List of Extra Field names corresponding to header IDs. + * @var array + */ + protected $extraFieldNames = array( + self::EXTRA_ZIP64 => 'Zip64', + self::EXTRA_NTFS => 'NTFS', + self::EXTRA_UNIX => 'Unix', + self::EXTRA_STRONG_ENCR => 'Strong Encryption', + self::EXTRA_POSZIP => 'POSZIP', + self::EXTRA_UNIXTIME => 'Unix Time', + self::EXTRA_IZUNIX => 'Info-ZIP (UX)', + self::EXTRA_IZUNIX2 => 'Info-ZIP (Ux)', + self::EXTRA_IZUNIX3 => 'Info-ZIP (ux)', + self::EXTRA_WZ_AES => 'AES-256 Password Encryption', + ); + + /** + * List of Host OS names by type. + * @var array + */ + protected $hostOSNames = array( + self::OS_FAT => 'MS-DOS and OS/2 (FAT)', + self::OS_AMIGA => 'Amiga', + self::OS_VMS => 'OpenVMS', + self::OS_UNIX => 'Unix', + self::OS_VM_CMS => 'VM/CMS', + self::OS_ATARI => 'Atari', + self::OS_HPFS => 'OS/2 HPFS', + self::OS_MAC => 'Macintosh', + self::OS_Z_SYSTEM => 'Z-System', + self::OS_CPM => 'CP/M', + self::OS_NTFS => 'Windows NTFS', + self::OS_MVS => 'MVS (OS/390 - Z/OS)', + self::OS_VSE => 'VSE', + self::OS_ACORN => 'Acorn Risc', + self::OS_VFAT => 'VFAT', + self::OS_ALT_MVS => 'Alternative MVS', + self::OS_BEOS => 'BEOS', + self::OS_TANDEM => 'Tandem', + self::OS_OS400 => 'OS/400', + self::OS_OSX => 'OS X (Darwin)', + ); + + /** + * Is the archive Central Directory encrypted? + * @var boolean + */ + public $isEncrypted = false; + + /** + * Convenience method that outputs a summary list of the file/data information, + * useful for pretty-printing. + * + * @param boolean $full add file list to output? + * @param boolean $skipDirs should directory entries be skipped? + * @param boolean $central should Central File records be used? + * @return array file/data summary + */ + public function getSummary($full=false, $skipDirs=false, $central=false) + { + $summary = array( + 'file_name' => $this->file, + 'file_size' => $this->fileSize, + 'data_size' => $this->dataSize, + 'use_range' => "{$this->start}-{$this->end}", + 'file_count' => $this->fileCount, + ); + if ($full) { + $summary['file_list'] = $this->getFileList($skipDirs, $central); + } + if ($this->error) { + $summary['error'] = $this->error; + } + + return $summary; + } + + /** + * Returns a list of the ZIP records found in the file/data in human-readable + * format (for debugging purposes only). + * + * @return array|boolean list of stored records, or false if none available + */ + public function getRecords() + { + // Check that records are stored + if (empty($this->records)) {return false;} + + // Build the record list + $ret = array(); + + foreach ($this->records AS $record) { + + $r = array(); + $r['type_name'] = $this->recordNames[$record['type']]; + $r += $record; + + // Sanity check filename length + if (isset($r['file_name'])) {$r['file_name'] = substr($r['file_name'], 0, $this->maxFilenameLength);} + $ret[] = $r; + } + + return $ret; + } + + /** + * Parses the stored records and returns a list of each of the file entries, + * optionally using the Central Directory File record instead of the (more + * limited) Local File record data. Valid file records include directory entries, + * but these can be skipped. + * + * @return array list of file records, empty if none are available + */ + public function getFileList($skipDirs=false, $central=false) + { + $ret = array(); + foreach ($this->records as $record) { + if (($central && $record['type'] == self::RECORD_CENTRAL_FILE) + || (!$central && $record['type'] == self::RECORD_LOCAL_FILE) + ) { + if ($skipDirs && !empty($record['is_dir'])) {continue;} + $ret[] = $this->getFileRecordSummary($record); + } + } + + return $ret; + } + + /** + * Retrieves the raw data for the given filename. Note that this is only useful + * if the file hasn't been compressed or encrypted. + * + * @param string $filename name of the file to retrieve + * @return mixed file data, or false if no file records available + */ + public function getFileData($filename) + { + // Check that records are stored and data source is available + if (empty($this->records) || ($this->data == '' && $this->handle == null)) { + return false; + } + + // Get the absolute start/end positions + if (!($info = $this->getFileInfo($filename)) || empty($info['range'])) { + $this->error = "Could not find file info for: ({$filename})"; + return false; + } + $this->error = ''; + + return $this->getRange(explode('-', $info['range'])); + } + + /** + * Saves the raw data for the given filename to the given destination. Note that + * this is only useful if the file isn't compressed or encrypted. + * + * @param string $filename name of the file to extract + * @param string $destination full path of the file to create + * @return integer|boolean number of bytes saved or false on error + */ + public function saveFileData($filename, $destination) + { + // Check that records are stored and data source is available + if (empty($this->records) || ($this->data == '' && $this->handle == null)) { + return false; + } + + // Get the absolute start/end positions + if (!($info = $this->getFileInfo($filename)) || empty($info['range'])) { + $this->error = "Could not find file info for: ({$filename})"; + return false; + } + $this->error = ''; + + return $this->saveRange(explode('-', $info['range']), $destination); + } + + /** + * Sets the absolute path to the external 7za client. + * + * @param string $client path to the client + * @return void + * @throws InvalidArgumentException + */ + public function setExternalClient($client) + { + if ($client && (!is_file($client) || !is_executable($client))) + throw new InvalidArgumentException("Not a valid client: {$client}"); + + $this->externalClient = $client; + } + + /** + * Extracts a compressed or encrypted file using the configured external 7za + * client, optionally returning the data or saving it to file. + * + * @param string $filename name of the file to extract + * @param string $destination full path of the file to create + * @param string $password password to use for decryption + * @return mixed extracted data, number of bytes saved or false on error + */ + public function extractFile($filename, $destination=null, $password=null) + { + if (!$this->externalClient || (!$this->file && !$this->data)) { + $this->error = 'An external client and valid data source are needed'; + return false; + } + + // Check that the file is extractable + if (!($info = $this->getFileInfo($filename))) { + $this->error = "Could not find file info for: ({$filename})"; + return false; + } + if (!empty($info['pass']) && $password == null) { + $this->error = "The file is passworded: ({$filename})"; + return false; + } + + // Set the data file source + $source = $this->file ? $this->file : $this->createTempDataFile(); + + // Set the external command + $pass = $password ? '-p'.escapeshellarg($password) : ''; + $command = '"'.$this->externalClient.'"' + ." e -so -bd -y -tzip {$pass} -- " + .escapeshellarg($source).' '.escapeshellarg($filename); + + // Set STDERR to write to a temporary file + list($hash, $errorFile) = $this->getTempFileName($source.'errors'); + $this->tempFiles[$hash] = $errorFile; + $command .= ' 2> '.escapeshellarg($errorFile); + + // Start the new pipe reader + $pipe = new PipeReader; + if (!$pipe->open($command)) { + $this->error = $pipe->error; + return false; + } + $this->error = ''; + + // Open destination file or start buffer + if ($destination) { + $handle = fopen($destination, 'wb'); + $written = 0; + } else { + $data = ''; + } + + // Buffer the piped data or save it to file + while ($read = $pipe->read(1024, false)) { + if ($destination) { + $written += fwrite($handle, $read); + } else { + $data .= $read; + } + } + if ($destination) {fclose($handle);} + $pipe->close(); + + // Check for errors (only after the pipe is closed) + if (($error = @file_get_contents($errorFile)) && strpos($error, 'Everything is Ok') === false) { + if ($destination) {@unlink($destination);} + $this->error = $error; + return false; + } + + return $destination ? $written : $data; + } + + /** + * List of records found in the file/data. + * @var array + */ + protected $records = array(); + + /** + * Full path to the external 7za client. + * @var string + */ + protected $externalClient = ''; + + /** + * Returns a processed summary of a Local or Central File record. + * + * @param array $record a valid file record + * @return array summary information + */ + protected function getFileRecordSummary($record) + { + $ret = array( + 'name' => substr($record['file_name'], 0, $this->maxFilenameLength), + 'size' => $record['uncompressed_size'], + 'date' => self::dos2unixtime(($record['last_mod_date'] << 16) | $record['last_mod_time']), + 'pass' => isset($record['is_encrypted']) ? ((int) $record['is_encrypted']) : 0, + 'compressed' => (int) ($record['method'] > 0), + 'next_offset' => $record['next_offset'], + ); + if (!empty($record['is_dir'])) { + $ret['is_dir'] = 1; + } elseif ($record['type'] == self::RECORD_LOCAL_FILE) { + $start = $this->start + $record['offset'] + 30 + $record['file_name_length'] + $record['extra_length']; + $end = min($this->end, $start + $record['uncompressed_size'] - 1); + $ret['range'] = "{$start}-{$end}"; + } + if (!empty($record['crc32'])) { + $ret['crc32'] = dechex($record['crc32']); + } + + return $ret; + } + + /** + * Returns information for the given filename in the current file/data. + * + * @param string $filename the filename to search + * @return array|boolean the file info or false on error + */ + protected function getFileInfo($filename) + { + foreach ($this->getFileList(true) as $file) { + if (isset($file['name']) && $file['name'] == $filename) { + return $file; + } + } + return false; + } + + /** + * Returns the position of the starting record signature in the file/data. + * An 'empty' ZIP file consists only of an End of Central Directory record. + * + * @return mixed start position, or false if no valid signature found + */ + public function findMarker() + { + if ($this->markerPosition !== null) + return $this->markerPosition; + + // Buffer the data to search + try { + $buff = $this->read(min($this->length, $this->maxReadBytes)); + $this->rewind(); + } catch (Exception $e) { + return false; + } + + // Try to find the first Local File or Central File record + if (($pos = strpos($buff, pack('V', self::RECORD_LOCAL_FILE))) !== false + || ($pos = strpos($buff, pack('V', self::RECORD_CENTRAL_FILE))) !== false + ) { + return $this->markerPosition = $pos; + } + + // Otherwise this could be an empty ZIP file + return $this->markerPosition = strpos($buff, pack('V', self::RECORD_ENDCENTRAL)); + } + + /** + * Parses the ZIP data and stores a list of valid records locally. + * + * @return boolean false if parsing fails + */ + protected function analyze() + { + // Find the first record signature, if there is one + if (($startPos = $this->findMarker()) === false) { + $this->error = 'Could not find any records, not a valid ZIP file'; + return false; + } + $this->seek($startPos); + + // Analyze all records + while ($this->offset < $this->length) try { + + // Get the next record header + if (($record = $this->getNextRecord()) === false) + continue; + + // Process the current record by type + $this->processRecord($record); + + // Add the current record to the list + $this->records[] = $record; + + // Skip to the next record, if any + if ($this->offset != $record['next_offset']) { + $this->seek($record['next_offset']); + } + + // Sanity check + if ($record['offset'] == $this->offset) { + $this->error = 'Parsing seems to be stuck'; + $this->close(); + return false; + } + + // No more readable data, or read error + } catch (Exception $e) { + if ($this->error) {$this->close(); return false;} + break; + } + + // Check for valid records + if (empty($this->records)) { + $this->error = 'No valid ZIP records were found'; + return false; + } + + // Analysis was successful + return true; + } + + /** + * Reads the start of the next record header and checks the header signature + * before further processing by record type. + * + * @return mixed the next record info, or false on invalid signature + */ + protected function getNextRecord() + { + // Start the record info + $record = array('offset' => $this->offset); + + // Unpack the record signature + $record += self::unpack('Vtype', $this->read(4)); + + // Check that the record signature is valid + if (!isset($this->recordNames[$record['type']])) { + $this->seek($this->offset - 3); + return false; + } + + // Return the record info + return $record; + } + + /** + * Processes a record passed by reference based on its type. We start with just + * the header signature, and unpack the rest of each header/body from there. + * + * @param array $record the record to process + * @return void + */ + protected function processRecord(&$record) + { + // Record type: LOCAL FILE + if ($record['type'] == self::RECORD_LOCAL_FILE) { + $record += self::unpack(self::FORMAT_LOCAL_FILE, $this->read(26)); + $record['file_name'] = $this->read($record['file_name_length']); + if ($record['extra_length'] > 0) { + $this->processExtraFields($record); + } + $record['next_offset'] = $this->offset + $record['compressed_size']; + $this->fileCount++; + + // Data Descriptor follows file data? + if ($record['flags'] & self::FILE_DESCRIPTOR_USED) { + $this->seek($record['next_offset']); + $descr = self::unpack(self::FORMAT_DATA_DESCR, $this->read(16)); + $record['has_descriptor'] = true; + $record['crc32'] = $descr['crc32']; + $record['compressed_size'] = $descr['compressed_size']; + $record['uncompressed_size'] = $descr['uncompressed_size']; + $record['next_offset'] = $this->offset; + } + } + + // Record type: CENTRAL FILE + elseif ($record['type'] == self::RECORD_CENTRAL_FILE) { + $record += self::unpack(self::FORMAT_CENTRAL_FILE, $this->read(42)); + $record['file_name'] = $this->read($record['file_name_length']); + if ($record['extra_length'] > 0) { + $this->processExtraFields($record); + } + if ($record['comment_length'] > 0) { + $record['comment'] = $this->read($record['comment_length']); + } + $record['next_offset'] = $this->offset; + } + + // Record type: END OF CENTRAL DIRECTORY + elseif ($record['type'] == self::RECORD_ENDCENTRAL) { + $record += self::unpack(self::FORMAT_ENDCENTRAL, $this->read(18)); + if ($record['comment_length'] > 0) { + $record['comment'] = $this->read($record['comment_length']); + } + $record['next_offset'] = $this->offset; + $this->fileCount = $record['entries_disk']; + } + + // Record type: ZIP64 END OF CENTRAL DIRECTORY + elseif ($record['type'] == self::RECORD_Z64_ENDCENTRAL) { + $record += self::unpack(self::FORMAT_Z64_ENDCENTRAL, $this->read(50)); + $record['next_offset'] = $record['offset'] + self::int64($record['central_size'], $record['central_size_high']); + $this->fileCount = self::int64($record['entries_disk'], $record['entries_disk_high']); + } + + // Record type: ZIP64 END OF CENTRAL DIRECTORY LOCATOR + elseif ($record['type'] == self::RECORD_Z64_ENDCENTRAL_LOC) { + $record += self::unpack(self::FORMAT_Z64_ENDCENTRAL_LOC, $this->read(16)); + $record['next_offset'] = $this->offset; + } + + // Skip everything else + else { + $record['next_offset'] = $this->offset + 1; + } + + // Process any version numbers (-> major.minor) + if (isset($record['version_made_num'])) { + $num = $record['version_made_num']; + $record['made_version'] = floor($num / 10).'.'.($num % 10); + } + if (isset($record['version_need_num'])) { + $num = $record['version_need_num']; + $record['need_version'] = floor($num / 10).'.'.($num % 10); + } + + // Process Host OS info + if (isset($record['version_made_os'])) { + $os = $record['version_made_os']; + $record['made_host_os'] = isset($this->hostOSNames[$os]) ? $this->hostOSNames[$os] : 'Unknown'; + } + if (isset($record['version_need_os'])) { + $os = $record['version_need_os']; + $record['need_host_os'] = isset($this->hostOSNames[$os]) ? $this->hostOSNames[$os] : 'Unknown'; + } + + if ($record['type'] == self::RECORD_LOCAL_FILE || $record['type'] == self::RECORD_CENTRAL_FILE) { + + // Is the file encrypted? + if ($record['flags'] & self::FILE_ENCRYPTED) { + $record['is_encrypted'] = true; + } + + // Is the Central Directory encrypted (masking Local File values)? + if ($record['flags'] & self::FILE_CDR_ENCRYPTED) { + $this->isEncrypted = true; + } + + // Is this a directory entry? (quick check) + if ($record['file_name'][$record['file_name_length'] - 1] == '/') { + $record['is_dir'] = true; + } + + // Is UTF8 encoding used? + if ($record['flags'] & self::FILE_EFS_UTF8) { + $record['is_utf8'] = true; + } + } + } + + /** + * Processes Extra Field blocks for the current record. + * + * @param array $record the current record to process + * @return void + */ + protected function processExtraFields(&$record) + { + $end = $this->offset + $record['extra_length']; + while ($this->offset < $end) + { + $field = array('type_name' => ''); + $field += self::unpack(self::FORMAT_EXTRA_FIELD, $this->read(4)); + $field['type_name'] = isset($this->extraFieldNames[$field['headerID']]) ? $this->extraFieldNames[$field['headerID']] : 'Unknown'; + + // Field: ZIP64 format + if ($field['headerID'] == self::EXTRA_ZIP64) { + + // Values are only included if the record values are set to 0xFFFFFFFF or 0xFFFF + if ($record['uncompressed_size'] == 0xFFFFFFFF) { + $field += self::unpack('Vuncompressed_size/Vuncompressed_size_high', $this->read(8)); + $record['uncompressed_size'] = self::int64($field['uncompressed_size'], $field['uncompressed_size_high']); + } + if ($record['compressed_size'] == 0xFFFFFFFF) { + $field += self::unpack('Vcompressed_size/Vcompressed_size_high', $this->read(8)); + $record['compressed_size'] = self::int64($field['compressed_size'], $field['compressed_size_high']); + } + if (isset($record['rel_offset']) && $record['rel_offset'] == 0xFFFFFFFF) { + $field += self::unpack('Vrel_offset/Vrel_offset_high', $this->read(8)); + $record['rel_offset'] = self::int64($field['rel_offset'], $field['rel_offset_high']); + } + if (isset($record['disk_start']) && $record['disk_start'] == 0xFFFF) { + $field += self::unpack('Vdisk_start', $this->read(4)); + $record['disk_start'] = $field['disk_start']; + } + } + + // Field: UNIXTIME + elseif ($field['headerID'] == self::EXTRA_UNIXTIME) { + // Probably could do something with this + $this->read($field['data_size']); + + // Default: skip field + } else { + $this->read($field['data_size']); + } + + // Add the extra field info to the record + $field['end_offset'] = $this->offset; + $record['extra_fields'][] = $field; + } + } + + + /** + * Resets the instance variables before parsing new data. + * + * @return void + */ + protected function reset() + { + parent::reset(); + + $this->records = array(); + $this->isEncrypted = false; + } + +} // End ZipInfo class diff --git a/lib/simple_html_dom.php b/lib/copy_this/libs/simple_html_dom.php similarity index 100% rename from lib/simple_html_dom.php rename to lib/copy_this/libs/simple_html_dom.php diff --git a/lib/copy_this/www/lib/smarty/Smarty.class.php b/lib/copy_this/libs/smarty/Smarty.class.php similarity index 100% rename from lib/copy_this/www/lib/smarty/Smarty.class.php rename to lib/copy_this/libs/smarty/Smarty.class.php diff --git a/lib/copy_this/www/lib/smarty/SmartyBC.class.php b/lib/copy_this/libs/smarty/SmartyBC.class.php similarity index 100% rename from lib/copy_this/www/lib/smarty/SmartyBC.class.php rename to lib/copy_this/libs/smarty/SmartyBC.class.php diff --git a/lib/copy_this/www/lib/smarty/debug.tpl b/lib/copy_this/libs/smarty/debug.tpl similarity index 100% rename from lib/copy_this/www/lib/smarty/debug.tpl rename to lib/copy_this/libs/smarty/debug.tpl diff --git a/lib/copy_this/www/lib/smarty/plugins/block.textformat.php b/lib/copy_this/libs/smarty/plugins/block.textformat.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/block.textformat.php rename to lib/copy_this/libs/smarty/plugins/block.textformat.php diff --git a/lib/copy_this/www/lib/smarty/plugins/function.counter.php b/lib/copy_this/libs/smarty/plugins/function.counter.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/function.counter.php rename to lib/copy_this/libs/smarty/plugins/function.counter.php diff --git a/lib/copy_this/www/lib/smarty/plugins/function.cycle.php b/lib/copy_this/libs/smarty/plugins/function.cycle.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/function.cycle.php rename to lib/copy_this/libs/smarty/plugins/function.cycle.php diff --git a/lib/copy_this/www/lib/smarty/plugins/function.fetch.php b/lib/copy_this/libs/smarty/plugins/function.fetch.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/function.fetch.php rename to lib/copy_this/libs/smarty/plugins/function.fetch.php diff --git a/lib/copy_this/www/lib/smarty/plugins/function.html_checkboxes.php b/lib/copy_this/libs/smarty/plugins/function.html_checkboxes.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/function.html_checkboxes.php rename to lib/copy_this/libs/smarty/plugins/function.html_checkboxes.php diff --git a/lib/copy_this/www/lib/smarty/plugins/function.html_image.php b/lib/copy_this/libs/smarty/plugins/function.html_image.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/function.html_image.php rename to lib/copy_this/libs/smarty/plugins/function.html_image.php diff --git a/lib/copy_this/www/lib/smarty/plugins/function.html_options.php b/lib/copy_this/libs/smarty/plugins/function.html_options.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/function.html_options.php rename to lib/copy_this/libs/smarty/plugins/function.html_options.php diff --git a/lib/copy_this/www/lib/smarty/plugins/function.html_options_multiple.php b/lib/copy_this/libs/smarty/plugins/function.html_options_multiple.php similarity index 99% rename from lib/copy_this/www/lib/smarty/plugins/function.html_options_multiple.php rename to lib/copy_this/libs/smarty/plugins/function.html_options_multiple.php index 3446dd9a3..826ec3bd2 100644 --- a/lib/copy_this/www/lib/smarty/plugins/function.html_options_multiple.php +++ b/lib/copy_this/libs/smarty/plugins/function.html_options_multiple.php @@ -170,5 +170,4 @@ function smarty_function_html_options_multiple_optgroup($key, $values, $selected } $optgroup_html .= "\n"; return $optgroup_html; -} -?> \ No newline at end of file +} \ No newline at end of file diff --git a/lib/copy_this/www/lib/smarty/plugins/function.html_radios.php b/lib/copy_this/libs/smarty/plugins/function.html_radios.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/function.html_radios.php rename to lib/copy_this/libs/smarty/plugins/function.html_radios.php diff --git a/lib/copy_this/www/lib/smarty/plugins/function.html_select_date.php b/lib/copy_this/libs/smarty/plugins/function.html_select_date.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/function.html_select_date.php rename to lib/copy_this/libs/smarty/plugins/function.html_select_date.php diff --git a/lib/copy_this/www/lib/smarty/plugins/function.html_select_time.php b/lib/copy_this/libs/smarty/plugins/function.html_select_time.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/function.html_select_time.php rename to lib/copy_this/libs/smarty/plugins/function.html_select_time.php diff --git a/lib/copy_this/www/lib/smarty/plugins/function.html_table.php b/lib/copy_this/libs/smarty/plugins/function.html_table.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/function.html_table.php rename to lib/copy_this/libs/smarty/plugins/function.html_table.php diff --git a/lib/copy_this/www/lib/smarty/plugins/function.mailto.php b/lib/copy_this/libs/smarty/plugins/function.mailto.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/function.mailto.php rename to lib/copy_this/libs/smarty/plugins/function.mailto.php diff --git a/lib/copy_this/www/lib/smarty/plugins/function.math.php b/lib/copy_this/libs/smarty/plugins/function.math.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/function.math.php rename to lib/copy_this/libs/smarty/plugins/function.math.php diff --git a/lib/copy_this/www/lib/smarty/plugins/modifier.capitalize.php b/lib/copy_this/libs/smarty/plugins/modifier.capitalize.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/modifier.capitalize.php rename to lib/copy_this/libs/smarty/plugins/modifier.capitalize.php diff --git a/lib/copy_this/www/lib/smarty/plugins/modifier.date_format.php b/lib/copy_this/libs/smarty/plugins/modifier.date_format.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/modifier.date_format.php rename to lib/copy_this/libs/smarty/plugins/modifier.date_format.php diff --git a/lib/copy_this/www/lib/smarty/plugins/modifier.debug_print_var.php b/lib/copy_this/libs/smarty/plugins/modifier.debug_print_var.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/modifier.debug_print_var.php rename to lib/copy_this/libs/smarty/plugins/modifier.debug_print_var.php diff --git a/lib/copy_this/www/lib/smarty/plugins/modifier.escape.php b/lib/copy_this/libs/smarty/plugins/modifier.escape.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/modifier.escape.php rename to lib/copy_this/libs/smarty/plugins/modifier.escape.php diff --git a/lib/copy_this/www/lib/smarty/plugins/modifier.regex_replace.php b/lib/copy_this/libs/smarty/plugins/modifier.regex_replace.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/modifier.regex_replace.php rename to lib/copy_this/libs/smarty/plugins/modifier.regex_replace.php diff --git a/lib/copy_this/www/lib/smarty/plugins/modifier.replace.php b/lib/copy_this/libs/smarty/plugins/modifier.replace.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/modifier.replace.php rename to lib/copy_this/libs/smarty/plugins/modifier.replace.php diff --git a/lib/copy_this/www/lib/smarty/plugins/modifier.spacify.php b/lib/copy_this/libs/smarty/plugins/modifier.spacify.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/modifier.spacify.php rename to lib/copy_this/libs/smarty/plugins/modifier.spacify.php diff --git a/lib/copy_this/www/lib/smarty/plugins/modifier.truncate.php b/lib/copy_this/libs/smarty/plugins/modifier.truncate.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/modifier.truncate.php rename to lib/copy_this/libs/smarty/plugins/modifier.truncate.php diff --git a/lib/copy_this/www/lib/smarty/plugins/modifiercompiler.cat.php b/lib/copy_this/libs/smarty/plugins/modifiercompiler.cat.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/modifiercompiler.cat.php rename to lib/copy_this/libs/smarty/plugins/modifiercompiler.cat.php diff --git a/lib/copy_this/www/lib/smarty/plugins/modifiercompiler.count_characters.php b/lib/copy_this/libs/smarty/plugins/modifiercompiler.count_characters.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/modifiercompiler.count_characters.php rename to lib/copy_this/libs/smarty/plugins/modifiercompiler.count_characters.php diff --git a/lib/copy_this/www/lib/smarty/plugins/modifiercompiler.count_paragraphs.php b/lib/copy_this/libs/smarty/plugins/modifiercompiler.count_paragraphs.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/modifiercompiler.count_paragraphs.php rename to lib/copy_this/libs/smarty/plugins/modifiercompiler.count_paragraphs.php diff --git a/lib/copy_this/www/lib/smarty/plugins/modifiercompiler.count_sentences.php b/lib/copy_this/libs/smarty/plugins/modifiercompiler.count_sentences.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/modifiercompiler.count_sentences.php rename to lib/copy_this/libs/smarty/plugins/modifiercompiler.count_sentences.php diff --git a/lib/copy_this/www/lib/smarty/plugins/modifiercompiler.count_words.php b/lib/copy_this/libs/smarty/plugins/modifiercompiler.count_words.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/modifiercompiler.count_words.php rename to lib/copy_this/libs/smarty/plugins/modifiercompiler.count_words.php diff --git a/lib/copy_this/www/lib/smarty/plugins/modifiercompiler.default.php b/lib/copy_this/libs/smarty/plugins/modifiercompiler.default.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/modifiercompiler.default.php rename to lib/copy_this/libs/smarty/plugins/modifiercompiler.default.php diff --git a/lib/copy_this/www/lib/smarty/plugins/modifiercompiler.escape.php b/lib/copy_this/libs/smarty/plugins/modifiercompiler.escape.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/modifiercompiler.escape.php rename to lib/copy_this/libs/smarty/plugins/modifiercompiler.escape.php diff --git a/lib/copy_this/www/lib/smarty/plugins/modifiercompiler.from_charset.php b/lib/copy_this/libs/smarty/plugins/modifiercompiler.from_charset.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/modifiercompiler.from_charset.php rename to lib/copy_this/libs/smarty/plugins/modifiercompiler.from_charset.php diff --git a/lib/copy_this/www/lib/smarty/plugins/modifiercompiler.indent.php b/lib/copy_this/libs/smarty/plugins/modifiercompiler.indent.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/modifiercompiler.indent.php rename to lib/copy_this/libs/smarty/plugins/modifiercompiler.indent.php diff --git a/lib/copy_this/www/lib/smarty/plugins/modifiercompiler.lower.php b/lib/copy_this/libs/smarty/plugins/modifiercompiler.lower.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/modifiercompiler.lower.php rename to lib/copy_this/libs/smarty/plugins/modifiercompiler.lower.php diff --git a/lib/copy_this/www/lib/smarty/plugins/modifiercompiler.noprint.php b/lib/copy_this/libs/smarty/plugins/modifiercompiler.noprint.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/modifiercompiler.noprint.php rename to lib/copy_this/libs/smarty/plugins/modifiercompiler.noprint.php diff --git a/lib/copy_this/www/lib/smarty/plugins/modifiercompiler.string_format.php b/lib/copy_this/libs/smarty/plugins/modifiercompiler.string_format.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/modifiercompiler.string_format.php rename to lib/copy_this/libs/smarty/plugins/modifiercompiler.string_format.php diff --git a/lib/copy_this/www/lib/smarty/plugins/modifiercompiler.strip.php b/lib/copy_this/libs/smarty/plugins/modifiercompiler.strip.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/modifiercompiler.strip.php rename to lib/copy_this/libs/smarty/plugins/modifiercompiler.strip.php diff --git a/lib/copy_this/www/lib/smarty/plugins/modifiercompiler.strip_tags.php b/lib/copy_this/libs/smarty/plugins/modifiercompiler.strip_tags.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/modifiercompiler.strip_tags.php rename to lib/copy_this/libs/smarty/plugins/modifiercompiler.strip_tags.php diff --git a/lib/copy_this/www/lib/smarty/plugins/modifiercompiler.to_charset.php b/lib/copy_this/libs/smarty/plugins/modifiercompiler.to_charset.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/modifiercompiler.to_charset.php rename to lib/copy_this/libs/smarty/plugins/modifiercompiler.to_charset.php diff --git a/lib/copy_this/www/lib/smarty/plugins/modifiercompiler.unescape.php b/lib/copy_this/libs/smarty/plugins/modifiercompiler.unescape.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/modifiercompiler.unescape.php rename to lib/copy_this/libs/smarty/plugins/modifiercompiler.unescape.php diff --git a/lib/copy_this/www/lib/smarty/plugins/modifiercompiler.upper.php b/lib/copy_this/libs/smarty/plugins/modifiercompiler.upper.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/modifiercompiler.upper.php rename to lib/copy_this/libs/smarty/plugins/modifiercompiler.upper.php diff --git a/lib/copy_this/www/lib/smarty/plugins/modifiercompiler.wordwrap.php b/lib/copy_this/libs/smarty/plugins/modifiercompiler.wordwrap.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/modifiercompiler.wordwrap.php rename to lib/copy_this/libs/smarty/plugins/modifiercompiler.wordwrap.php diff --git a/lib/copy_this/www/lib/smarty/plugins/outputfilter.trimwhitespace.php b/lib/copy_this/libs/smarty/plugins/outputfilter.trimwhitespace.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/outputfilter.trimwhitespace.php rename to lib/copy_this/libs/smarty/plugins/outputfilter.trimwhitespace.php diff --git a/lib/copy_this/www/lib/smarty/plugins/shared.escape_special_chars.php b/lib/copy_this/libs/smarty/plugins/shared.escape_special_chars.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/shared.escape_special_chars.php rename to lib/copy_this/libs/smarty/plugins/shared.escape_special_chars.php diff --git a/lib/copy_this/www/lib/smarty/plugins/shared.literal_compiler_param.php b/lib/copy_this/libs/smarty/plugins/shared.literal_compiler_param.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/shared.literal_compiler_param.php rename to lib/copy_this/libs/smarty/plugins/shared.literal_compiler_param.php diff --git a/lib/copy_this/www/lib/smarty/plugins/shared.make_timestamp.php b/lib/copy_this/libs/smarty/plugins/shared.make_timestamp.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/shared.make_timestamp.php rename to lib/copy_this/libs/smarty/plugins/shared.make_timestamp.php diff --git a/lib/copy_this/www/lib/smarty/plugins/shared.mb_str_replace.php b/lib/copy_this/libs/smarty/plugins/shared.mb_str_replace.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/shared.mb_str_replace.php rename to lib/copy_this/libs/smarty/plugins/shared.mb_str_replace.php diff --git a/lib/copy_this/www/lib/smarty/plugins/shared.mb_unicode.php b/lib/copy_this/libs/smarty/plugins/shared.mb_unicode.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/shared.mb_unicode.php rename to lib/copy_this/libs/smarty/plugins/shared.mb_unicode.php diff --git a/lib/copy_this/www/lib/smarty/plugins/shared.mb_wordwrap.php b/lib/copy_this/libs/smarty/plugins/shared.mb_wordwrap.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/shared.mb_wordwrap.php rename to lib/copy_this/libs/smarty/plugins/shared.mb_wordwrap.php diff --git a/lib/copy_this/www/lib/smarty/plugins/variablefilter.htmlspecialchars.php b/lib/copy_this/libs/smarty/plugins/variablefilter.htmlspecialchars.php similarity index 100% rename from lib/copy_this/www/lib/smarty/plugins/variablefilter.htmlspecialchars.php rename to lib/copy_this/libs/smarty/plugins/variablefilter.htmlspecialchars.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_cacheresource.php b/lib/copy_this/libs/smarty/sysplugins/smarty_cacheresource.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_cacheresource.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_cacheresource.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_cacheresource_custom.php b/lib/copy_this/libs/smarty/sysplugins/smarty_cacheresource_custom.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_cacheresource_custom.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_cacheresource_custom.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_cacheresource_keyvaluestore.php b/lib/copy_this/libs/smarty/sysplugins/smarty_cacheresource_keyvaluestore.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_cacheresource_keyvaluestore.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_cacheresource_keyvaluestore.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_config_source.php b/lib/copy_this/libs/smarty/sysplugins/smarty_config_source.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_config_source.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_config_source.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_cacheresource_file.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_cacheresource_file.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_cacheresource_file.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_cacheresource_file.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_append.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_append.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_append.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_append.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_assign.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_assign.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_assign.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_assign.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_block.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_block.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_block.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_block.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_break.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_break.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_break.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_break.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_call.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_call.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_call.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_call.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_capture.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_capture.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_capture.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_capture.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_config_load.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_config_load.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_config_load.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_config_load.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_continue.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_continue.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_continue.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_continue.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_debug.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_debug.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_debug.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_debug.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_eval.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_eval.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_eval.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_eval.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_extends.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_extends.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_extends.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_extends.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_for.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_for.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_for.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_for.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_foreach.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_foreach.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_foreach.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_foreach.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_function.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_function.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_function.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_function.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_if.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_if.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_if.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_if.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_include.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_include.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_include.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_include.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_include_php.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_include_php.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_include_php.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_include_php.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_insert.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_insert.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_insert.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_insert.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_ldelim.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_ldelim.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_ldelim.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_ldelim.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_nocache.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_nocache.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_nocache.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_nocache.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_private_block_plugin.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_private_block_plugin.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_private_block_plugin.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_private_block_plugin.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_private_function_plugin.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_private_function_plugin.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_private_function_plugin.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_private_function_plugin.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_private_modifier.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_private_modifier.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_private_modifier.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_private_modifier.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_private_object_block_function.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_private_object_block_function.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_private_object_block_function.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_private_object_block_function.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_private_object_function.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_private_object_function.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_private_object_function.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_private_object_function.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_private_print_expression.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_private_print_expression.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_private_print_expression.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_private_print_expression.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_private_registered_block.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_private_registered_block.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_private_registered_block.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_private_registered_block.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_private_registered_function.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_private_registered_function.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_private_registered_function.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_private_registered_function.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_private_special_variable.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_private_special_variable.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_private_special_variable.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_private_special_variable.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_rdelim.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_rdelim.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_rdelim.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_rdelim.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_section.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_section.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_section.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_section.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_setfilter.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_setfilter.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_setfilter.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_setfilter.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_while.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_while.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compile_while.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_compile_while.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compilebase.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_compilebase.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_compilebase.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_compilebase.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_config.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_config.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_config.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_config.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_config_file_compiler.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_config_file_compiler.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_config_file_compiler.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_config_file_compiler.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_configfilelexer.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_configfilelexer.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_configfilelexer.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_configfilelexer.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_configfileparser.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_configfileparser.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_configfileparser.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_configfileparser.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_data.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_data.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_data.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_data.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_debug.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_debug.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_debug.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_debug.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_filter_handler.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_filter_handler.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_filter_handler.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_filter_handler.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_function_call_handler.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_function_call_handler.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_function_call_handler.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_function_call_handler.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_get_include_path.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_get_include_path.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_get_include_path.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_get_include_path.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_nocache_insert.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_nocache_insert.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_nocache_insert.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_nocache_insert.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_parsetree.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_parsetree.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_parsetree.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_parsetree.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_resource_eval.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_resource_eval.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_resource_eval.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_resource_eval.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_resource_extends.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_resource_extends.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_resource_extends.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_resource_extends.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_resource_file.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_resource_file.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_resource_file.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_resource_file.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_resource_php.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_resource_php.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_resource_php.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_resource_php.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_resource_registered.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_resource_registered.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_resource_registered.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_resource_registered.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_resource_stream.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_resource_stream.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_resource_stream.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_resource_stream.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_resource_string.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_resource_string.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_resource_string.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_resource_string.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_smartytemplatecompiler.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_smartytemplatecompiler.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_smartytemplatecompiler.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_smartytemplatecompiler.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_template.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_template.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_template.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_template.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_templatebase.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_templatebase.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_templatebase.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_templatebase.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_templatecompilerbase.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_templatecompilerbase.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_templatecompilerbase.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_templatecompilerbase.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_templatelexer.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_templatelexer.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_templatelexer.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_templatelexer.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_templateparser.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_templateparser.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_templateparser.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_templateparser.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_utility.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_utility.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_utility.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_utility.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_write_file.php b/lib/copy_this/libs/smarty/sysplugins/smarty_internal_write_file.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_internal_write_file.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_internal_write_file.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_resource.php b/lib/copy_this/libs/smarty/sysplugins/smarty_resource.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_resource.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_resource.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_resource_custom.php b/lib/copy_this/libs/smarty/sysplugins/smarty_resource_custom.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_resource_custom.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_resource_custom.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_resource_recompiled.php b/lib/copy_this/libs/smarty/sysplugins/smarty_resource_recompiled.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_resource_recompiled.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_resource_recompiled.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_resource_uncompiled.php b/lib/copy_this/libs/smarty/sysplugins/smarty_resource_uncompiled.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_resource_uncompiled.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_resource_uncompiled.php diff --git a/lib/copy_this/www/lib/smarty/sysplugins/smarty_security.php b/lib/copy_this/libs/smarty/sysplugins/smarty_security.php similarity index 100% rename from lib/copy_this/www/lib/smarty/sysplugins/smarty_security.php rename to lib/copy_this/libs/smarty/sysplugins/smarty_security.php diff --git a/lib/copy_this/misc/reqscraper/config.dist.php b/lib/copy_this/misc/reqscraper/config.dist.php new file mode 100644 index 000000000..6103264b6 --- /dev/null +++ b/lib/copy_this/misc/reqscraper/config.dist.php @@ -0,0 +1,15 @@ + +Copyright (c): 1999-2000 ispi, all rights reserved +Version: 1.0 + + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +You may contact the author of Snoopy by e-mail at: +monte@ispi.net + +Or, write to: +Monte Ohrt +CTO, ispi +237 S. 70th suite 220 +Lincoln, NE 68510 + +The latest version of Snoopy can be obtained from: +http://snoopy.sourceforge.com + +*************************************************/ + +class Snoopy +{ + /**** Public variables ****/ + + /* user definable vars */ + + var $host = "www.php.net"; // host name we are connecting to + var $port = 80; // port we are connecting to + var $proxy_host = ""; // proxy host to use + var $proxy_port = ""; // proxy port to use + var $agent = "Snoopy v1.0"; // agent we masquerade as + var $referer = ""; // referer info to pass + var $cookies = array(); // array of cookies to pass + // $cookies["username"]="joe"; + var $rawheaders = array(); // array of raw headers to send + // $rawheaders["Content-type"]="text/html"; + + var $maxredirs = 5; // http redirection depth maximum. 0 = disallow + var $lastredirectaddr = ""; // contains address of last redirected address + var $offsiteok = true; // allows redirection off-site + var $maxframes = 0; // frame content depth maximum. 0 = disallow + var $expandlinks = true; // expand links to fully qualified URLs. + // this only applies to fetchlinks() + // or submitlinks() + var $passcookies = true; // pass set cookies back through redirects + // NOTE: this currently does not respect + // dates, domains or paths. + + var $user = ""; // user for http authentication + var $pass = ""; // password for http authentication + + // http accept types + var $accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*"; + + var $results = ""; // where the content is put + + var $error = ""; // error messages sent here + var $response_code = ""; // response code returned from server + var $headers = array(); // headers returned from server sent here + var $maxlength = 500000; // max return data length (body) + var $read_timeout = 0; // timeout on read operations, in seconds + // supported only since PHP 4 Beta 4 + // set to 0 to disallow timeouts + var $timed_out = false; // if a read operation timed out + var $status = 0; // http request status + + var $curl_path = "/usr/bin/curl"; + // Snoopy will use cURL for fetching + // SSL content if a full system path to + // the cURL binary is supplied here. + // set to false if you do not have + // cURL installed. See http://curl.haxx.se + // for details on installing cURL. + // Snoopy does *not* use the cURL + // library functions built into php, + // as these functions are not stable + // as of this Snoopy release. + + // send Accept-encoding: gzip? + var $use_gzip = true; + + /**** Private variables ****/ + + var $_maxlinelen = 4096; // max line length (headers) + + var $_httpmethod = "GET"; // default http request method + var $_httpversion = "HTTP/1.0"; // default http request version + var $_submit_method = "POST"; // default submit method + var $_submit_type = "application/x-www-form-urlencoded"; // default submit type + var $_mime_boundary = ""; // MIME boundary for multipart/form-data submit type + var $_redirectaddr = false; // will be set if page fetched is a redirect + var $_redirectdepth = 0; // increments on an http redirect + var $_frameurls = array(); // frame src urls + var $_framedepth = 0; // increments on frame depth + + var $_isproxy = false; // set if using a proxy server + var $_fp_timeout = 30; // timeout for socket connection + +/*======================================================================*\ + Function: fetch + Purpose: fetch the contents of a web page + (and possibly other protocols in the + future like ftp, nntp, gopher, etc.) + Input: $URI the location of the page to fetch + Output: $this->results the output text from the fetch +\*======================================================================*/ + + function fetch($URI) + { + + //preg_match("|^([^:]+)://([^:/]+)(:[\d]+)*(.*)|",$URI,$URI_PARTS); + $URI_PARTS = parse_url($URI); + if (!empty($URI_PARTS["user"])) + $this->user = $URI_PARTS["user"]; + if (!empty($URI_PARTS["pass"])) + $this->pass = $URI_PARTS["pass"]; + + switch($URI_PARTS["scheme"]) + { + case "http": + $this->host = $URI_PARTS["host"]; + if(!empty($URI_PARTS["port"])) + $this->port = $URI_PARTS["port"]; + if($this->_connect($fp)) + { + if($this->_isproxy) + { + // using proxy, send entire URI + $this->_httprequest($URI,$fp,$URI,$this->_httpmethod); + } + else + { + $path = $URI_PARTS["path"].(isset($URI_PARTS["query"]) ? "?".$URI_PARTS["query"] : ""); + // no proxy, send only the path + $this->_httprequest($path, $fp, $URI, $this->_httpmethod); + } + + $this->_disconnect($fp); + + if($this->_redirectaddr) + { + /* url was redirected, check if we've hit the max depth */ + if($this->maxredirs > $this->_redirectdepth) + { + // only follow redirect if it's on this site, or offsiteok is true + if(preg_match("|^http://".preg_quote($this->host)."|i",$this->_redirectaddr) || $this->offsiteok) + { + /* follow the redirect */ + $this->_redirectdepth++; + $this->lastredirectaddr=$this->_redirectaddr; + $this->fetch($this->_redirectaddr); + } + } + } + + if($this->_framedepth < $this->maxframes && count($this->_frameurls) > 0) + { + $frameurls = $this->_frameurls; + $this->_frameurls = array(); + + while(list(,$frameurl) = each($frameurls)) + { + if($this->_framedepth < $this->maxframes) + { + $this->fetch($frameurl); + $this->_framedepth++; + } + else + break; + } + } + } + else + { + return false; + } + return true; + break; + case "https": + if(!$this->curl_path || (!is_executable($this->curl_path))) { + $this->error = "Bad curl ($this->curl_path), can't fetch HTTPS \n"; + return false; + } + $this->host = $URI_PARTS["host"]; + if(!empty($URI_PARTS["port"])) + $this->port = $URI_PARTS["port"]; + if($this->_isproxy) + { + // using proxy, send entire URI + $this->_httpsrequest($URI,$URI,$this->_httpmethod); + } + else + { + $path = $URI_PARTS["path"].($URI_PARTS["query"] ? "?".$URI_PARTS["query"] : ""); + // no proxy, send only the path + $this->_httpsrequest($path, $URI, $this->_httpmethod); + } + + if($this->_redirectaddr) + { + /* url was redirected, check if we've hit the max depth */ + if($this->maxredirs > $this->_redirectdepth) + { + // only follow redirect if it's on this site, or offsiteok is true + if(preg_match("|^http://".preg_quote($this->host)."|i",$this->_redirectaddr) || $this->offsiteok) + { + /* follow the redirect */ + $this->_redirectdepth++; + $this->lastredirectaddr=$this->_redirectaddr; + $this->fetch($this->_redirectaddr); + } + } + } + + if($this->_framedepth < $this->maxframes && count($this->_frameurls) > 0) + { + $frameurls = $this->_frameurls; + $this->_frameurls = array(); + + while(list(,$frameurl) = each($frameurls)) + { + if($this->_framedepth < $this->maxframes) + { + $this->fetch($frameurl); + $this->_framedepth++; + } + else + break; + } + } + return true; + break; + default: + // not a valid protocol + $this->error = 'Invalid protocol "'.$URI_PARTS["scheme"].'"\n'; + return false; + break; + } + return true; + } + + + +/*======================================================================*\ + Private functions +\*======================================================================*/ + + +/*======================================================================*\ + Function: _striplinks + Purpose: strip the hyperlinks from an html document + Input: $document document to strip. + Output: $match an array of the links +\*======================================================================*/ + + function _striplinks($document) + { + preg_match_all("'<\s*a\s+.*href\s*=\s* # find ]+)) # if quote found, match up to next matching + # quote, otherwise match up to next space + 'isx",$document,$links); + + + // catenate the non-empty matches from the conditional subpattern + + while(list($key,$val) = each($links[2])) + { + if(!empty($val)) + $match[] = $val; + } + + while(list($key,$val) = each($links[3])) + { + if(!empty($val)) + $match[] = $val; + } + + // return the links + return $match; + } + +/*======================================================================*\ + Function: _stripform + Purpose: strip the form elements from an html document + Input: $document document to strip. + Output: $match an array of the links +\*======================================================================*/ + + function _stripform($document) + { + preg_match_all("'<\/?(FORM|INPUT|SELECT|TEXTAREA|(OPTION))[^<>]*>(?(2)(.*(?=<\/?(option|select)[^<>]*>[\r\n]*)|(?=[\r\n]*))|(?=[\r\n]*))'Usi",$document,$elements); + + // catenate the matches + $match = implode("\r\n",$elements[0]); + + // return the links + return $match; + } + + + +/*======================================================================*\ + Function: _striptext + Purpose: strip the text from an html document + Input: $document document to strip. + Output: $text the resulting text +\*======================================================================*/ + + function _striptext($document) + { + + // I didn't use preg eval (//e) since that is only available in PHP 4.0. + // so, list your entities one by one here. I included some of the + // more common ones. + + $search = array("']*?>.*?'si", // strip out javascript + "'<[\/\!]*?[^<>]*?>'si", // strip out html tags + "'([\r\n])[\s]+'", // strip out white space + "'&(quote|#34);'i", // replace html entities + "'&(amp|#38);'i", + "'&(lt|#60);'i", + "'&(gt|#62);'i", + "'&(nbsp|#160);'i", + "'&(iexcl|#161);'i", + "'&(cent|#162);'i", + "'&(pound|#163);'i", + "'&(copy|#169);'i" + ); + $replace = array( "", + "", + "\\1", + "\"", + "&", + "<", + ">", + " ", + chr(161), + chr(162), + chr(163), + chr(169)); + + $text = preg_replace($search,$replace,$document); + + return $text; + } + +/*======================================================================*\ + Function: _expandlinks + Purpose: expand each link into a fully qualified URL + Input: $links the links to qualify + $URI the full URI to get the base from + Output: $expandedLinks the expanded links +\*======================================================================*/ + + function _expandlinks($links,$URI) + { + + preg_match("/^[^\?]+/",$URI,$match); + + $match = preg_replace("|/[^\/\.]+\.[^\/\.]+$|","",$match[0]); + + $search = array( "|^http://".preg_quote($this->host)."|i", + "|^(?!http://)(\/)?(?!mailto:)|i", + "|/\./|", + "|/[^\/]+/\.\./|" + ); + + $replace = array( "", + $match."/", + "/", + "/" + ); + + $expandedLinks = preg_replace($search,$replace,$links); + + return $expandedLinks; + } + +/*======================================================================*\ + Function: _httprequest + Purpose: go get the http data from the server + Input: $url the url to fetch + $fp the current open file pointer + $URI the full URI + $body body contents to send if any (POST) + Output: +\*======================================================================*/ + + function _httprequest($url,$fp,$URI,$http_method,$content_type="",$body="") + { + if($this->passcookies && $this->_redirectaddr) + $this->setcookies(); + + $URI_PARTS = parse_url($URI); + if(empty($url)) + $url = "/"; + $headers = $http_method." ".$url." ".$this->_httpversion."\r\n"; + if(!empty($this->agent)) + $headers .= "User-Agent: ".$this->agent."\r\n"; + if(!empty($this->host) && !isset($this->rawheaders['Host'])) + $headers .= "Host: ".$this->host."\r\n"; + if(!empty($this->accept)) + $headers .= "Accept: ".$this->accept."\r\n"; + + if($this->use_gzip) { + // make sure PHP was built with --with-zlib + // and we can handle gzipp'ed data + if ( function_exists(gzinflate) ) { + $headers .= "Accept-encoding: gzip\r\n"; + } + else { + trigger_error( + "use_gzip is on, but PHP was built without zlib support.". + " Requesting file(s) without gzip encoding.", + E_USER_NOTICE); + } + } + + if(!empty($this->referer)) + $headers .= "Referer: ".$this->referer."\r\n"; + if(!empty($this->cookies)) + { + if(!is_array($this->cookies)) + $this->cookies = (array)$this->cookies; + + reset($this->cookies); + if ( count($this->cookies) > 0 ) { + $cookie_headers .= 'Cookie: '; + foreach ( $this->cookies as $cookieKey => $cookieVal ) { + $cookie_headers .= $cookieKey."=".urlencode($cookieVal)."; "; + } + $headers .= substr($cookie_headers,0,-2) . "\r\n"; + } + } + if(!empty($this->rawheaders)) + { + if(!is_array($this->rawheaders)) + $this->rawheaders = (array)$this->rawheaders; + while(list($headerKey,$headerVal) = each($this->rawheaders)) + $headers .= $headerKey.": ".$headerVal."\r\n"; + } + if(!empty($content_type)) { + $headers .= "Content-type: $content_type"; + if ($content_type == "multipart/form-data") + $headers .= "; boundary=".$this->_mime_boundary; + $headers .= "\r\n"; + } + if(!empty($body)) + $headers .= "Content-length: ".strlen($body)."\r\n"; + if(!empty($this->user) || !empty($this->pass)) + $headers .= "Authorization: BASIC ".base64_encode($this->user.":".$this->pass)."\r\n"; + + $headers .= "\r\n"; + + // set the read timeout if needed + if ($this->read_timeout > 0) + socket_set_timeout($fp, $this->read_timeout); + $this->timed_out = false; + + fwrite($fp,$headers.$body,strlen($headers.$body)); + + $this->_redirectaddr = false; + unset($this->headers); + + // content was returned gzip encoded? + $is_gzipped = false; + + while($currentHeader = fgets($fp,$this->_maxlinelen)) + { + if ($this->read_timeout > 0 && $this->_check_timeout($fp)) + { + $this->status=-100; + return false; + } + + // if($currentHeader == "\r\n") + if(preg_match("/^\r?\n$/", $currentHeader) ) + break; + + // if a header begins with Location: or URI:, set the redirect + if(preg_match("/^(Location:|URI:)/i",$currentHeader)) + { + // get URL portion of the redirect + preg_match("/^(Location:|URI:)\s+(.*)/",chop($currentHeader),$matches); + // look for :// in the Location header to see if hostname is included + if(!preg_match("|\:\/\/|",$matches[2])) + { + // no host in the path, so prepend + $this->_redirectaddr = $URI_PARTS["scheme"]."://".$this->host.":".$this->port; + // eliminate double slash + if(!preg_match("|^/|",$matches[2])) + $this->_redirectaddr .= "/".$matches[2]; + else + $this->_redirectaddr .= $matches[2]; + } + else + $this->_redirectaddr = $matches[2]; + } + + if(preg_match("|^HTTP/|",$currentHeader)) + { + if(preg_match("|^HTTP/[^\s]*\s(.*?)\s|",$currentHeader, $status)) + { + $this->status= $status[1]; + } + $this->response_code = $currentHeader; + } + + if (preg_match("/Content-Encoding: gzip/", $currentHeader) ) { + $is_gzipped = true; + } + + $this->headers[] = $currentHeader; + } + + # $results = fread($fp, $this->maxlength); + $results = ""; + while ( $data = fread($fp, $this->maxlength) ) { + $results .= $data; + if ( + strlen($results) > $this->maxlength ) { + break; + } + } + + // gunzip + if ( $is_gzipped ) { + // per http://www.php.net/manual/en/function.gzencode.php + $results = substr($results, 10); + $results = gzinflate($results); + } + + if ($this->read_timeout > 0 && $this->_check_timeout($fp)) + { + $this->status=-100; + return false; + } + + // check if there is a a redirect meta tag + + if(preg_match("']*?content[\s]*=[\s]*[\"\']?\d+;[\s]+URL[\s]*=[\s]*([^\"\']*?)[\"\']?>'i",$results,$match)) + { + $this->_redirectaddr = $this->_expandlinks($match[1],$URI); + } + + // have we hit our frame depth and is there frame src to fetch? + if(($this->_framedepth < $this->maxframes) && preg_match_all("']+)'i",$results,$match)) + { + $this->results[] = $results; + for($x=0; $x_frameurls[] = $this->_expandlinks($match[1][$x],$URI_PARTS["scheme"]."://".$this->host); + } + // have we already fetched framed content? + elseif(is_array($this->results)) + $this->results[] = $results; + // no framed content + else + $this->results = $results; + + return true; + } + +/*======================================================================*\ + Function: _httpsrequest + Purpose: go get the https data from the server using curl + Input: $url the url to fetch + $URI the full URI + $body body contents to send if any (POST) + Output: +\*======================================================================*/ + + function _httpsrequest($url,$URI,$http_method,$content_type="",$body="") + { + if($this->passcookies && $this->_redirectaddr) + $this->setcookies(); + + $headers = array(); + + $URI_PARTS = parse_url($URI); + if(empty($url)) + $url = "/"; + // GET ... header not needed for curl + //$headers[] = $http_method." ".$url." ".$this->_httpversion; + if(!empty($this->agent)) + $headers[] = "User-Agent: ".$this->agent; + if(!empty($this->host)) + $headers[] = "Host: ".$this->host; + if(!empty($this->accept)) + $headers[] = "Accept: ".$this->accept; + if(!empty($this->referer)) + $headers[] = "Referer: ".$this->referer; + if(!empty($this->cookies)) + { + if(!is_array($this->cookies)) + $this->cookies = (array)$this->cookies; + + reset($this->cookies); + if ( count($this->cookies) > 0 ) { + $cookie_str = 'Cookie: '; + foreach ( $this->cookies as $cookieKey => $cookieVal ) { + $cookie_str .= $cookieKey."=".urlencode($cookieVal)."; "; + } + $headers[] = substr($cookie_str,0,-2); + } + } + if(!empty($this->rawheaders)) + { + if(!is_array($this->rawheaders)) + $this->rawheaders = (array)$this->rawheaders; + while(list($headerKey,$headerVal) = each($this->rawheaders)) + $headers[] = $headerKey.": ".$headerVal; + } + if(!empty($content_type)) { + if ($content_type == "multipart/form-data") + $headers[] = "Content-type: $content_type; boundary=".$this->_mime_boundary; + else + $headers[] = "Content-type: $content_type"; + } + if(!empty($body)) + $headers[] = "Content-length: ".strlen($body); + if(!empty($this->user) || !empty($this->pass)) + $headers[] = "Authorization: BASIC ".base64_encode($this->user.":".$this->pass); + + for($curr_header = 0; $curr_header < count($headers); $curr_header++) { + $cmdline_params .= " -H \"".$headers[$curr_header]."\""; + } + + if(!empty($body)) + $cmdline_params .= " -d \"$body\""; + + if($this->read_timeout > 0) + $cmdline_params .= " -m ".$this->read_timeout; + + $headerfile = uniqid(time()); + + # accept self-signed certs + $cmdline_params .= " -k"; + exec($this->curl_path." -D \"/tmp/$headerfile\"".escapeshellcmd($cmdline_params)." ".escapeshellcmd($URI),$results,$return); + + if($return) + { + $this->error = "Error: cURL could not retrieve the document, error $return."; + return false; + } + + + $results = implode("\r\n",$results); + + $result_headers = file("/tmp/$headerfile"); + + $this->_redirectaddr = false; + unset($this->headers); + + for($currentHeader = 0; $currentHeader < count($result_headers); $currentHeader++) + { + + // if a header begins with Location: or URI:, set the redirect + if(preg_match("/^(Location: |URI: )/i",$result_headers[$currentHeader])) + { + // get URL portion of the redirect + preg_match("/^(Location: |URI:)(.*)/",chop($result_headers[$currentHeader]),$matches); + // look for :// in the Location header to see if hostname is included + if(!preg_match("|\:\/\/|",$matches[2])) + { + // no host in the path, so prepend + $this->_redirectaddr = $URI_PARTS["scheme"]."://".$this->host.":".$this->port; + // eliminate double slash + if(!preg_match("|^/|",$matches[2])) + $this->_redirectaddr .= "/".$matches[2]; + else + $this->_redirectaddr .= $matches[2]; + } + else + $this->_redirectaddr = $matches[2]; + } + + if(preg_match("|^HTTP/|",$result_headers[$currentHeader])) + { + $this->response_code = $result_headers[$currentHeader]; + if(preg_match("|^HTTP/[^\s]*\s(.*?)\s|",$this->response_code, $match)) + { + $this->status= $match[1]; + } + } + $this->headers[] = $result_headers[$currentHeader]; + } + + // check if there is a a redirect meta tag + + if(preg_match("']*?content[\s]*=[\s]*[\"\']?\d+;[\s]+URL[\s]*=[\s]*([^\"\']*?)[\"\']?>'i",$results,$match)) + { + $this->_redirectaddr = $this->_expandlinks($match[1],$URI); + } + + // have we hit our frame depth and is there frame src to fetch? + if(($this->_framedepth < $this->maxframes) && preg_match_all("']+)'i",$results,$match)) + { + $this->results[] = $results; + for($x=0; $x_frameurls[] = $this->_expandlinks($match[1][$x],$URI_PARTS["scheme"]."://".$this->host); + } + // have we already fetched framed content? + elseif(is_array($this->results)) + $this->results[] = $results; + // no framed content + else + $this->results = $results; + + unlink("/tmp/$headerfile"); + + return true; + } + +/*======================================================================*\ + Function: setcookies() + Purpose: set cookies for a redirection +\*======================================================================*/ + + function setcookies() + { + for($x=0; $xheaders); $x++) + { + if(preg_match("/^set-cookie:[\s]+([^=]+)=([^;]+)/i", $this->headers[$x],$match)) + $this->cookies[$match[1]] = $match[2]; + } + } + + +/*======================================================================*\ + Function: _check_timeout + Purpose: checks whether timeout has occurred + Input: $fp file pointer +\*======================================================================*/ + + function _check_timeout($fp) + { + if ($this->read_timeout > 0) { + $fp_status = socket_get_status($fp); + if ($fp_status["timed_out"]) { + $this->timed_out = true; + return true; + } + } + return false; + } + +/*======================================================================*\ + Function: _connect + Purpose: make a socket connection + Input: $fp file pointer +\*======================================================================*/ + + function _connect(&$fp) + { + if(!empty($this->proxy_host) && !empty($this->proxy_port)) + { + $this->_isproxy = true; + $host = $this->proxy_host; + $port = $this->proxy_port; + } + else + { + $host = $this->host; + $port = $this->port; + } + + $this->status = 0; + + if($fp = fsockopen( + $host, + $port, + $errno, + $errstr, + $this->_fp_timeout + )) + { + // socket connection succeeded + + return true; + } + else + { + // socket connection failed + $this->status = $errno; + switch($errno) + { + case -3: + $this->error="socket creation failed (-3)"; + case -4: + $this->error="dns lookup failure (-4)"; + case -5: + $this->error="connection refused or timed out (-5)"; + default: + $this->error="connection failed (".$errno.")"; + } + return false; + } + } +/*======================================================================*\ + Function: _disconnect + Purpose: disconnect a socket connection + Input: $fp file pointer +\*======================================================================*/ + + function _disconnect($fp) + { + return(fclose($fp)); + } + + +/*======================================================================*\ + Function: _prepare_post_body + Purpose: Prepare post body according to encoding type + Input: $formvars - form variables + $formfiles - form upload files + Output: post body +\*======================================================================*/ + + function _prepare_post_body($formvars, $formfiles) + { + settype($formvars, "array"); + settype($formfiles, "array"); + + if (count($formvars) == 0 && count($formfiles) == 0) + return; + + switch ($this->_submit_type) { + case "application/x-www-form-urlencoded": + reset($formvars); + while(list($key,$val) = each($formvars)) { + if (is_array($val) || is_object($val)) { + while (list($cur_key, $cur_val) = each($val)) { + $postdata .= urlencode($key)."[]=".urlencode($cur_val)."&"; + } + } else + $postdata .= urlencode($key)."=".urlencode($val)."&"; + } + break; + + case "multipart/form-data": + $this->_mime_boundary = "Snoopy".md5(uniqid(microtime())); + + reset($formvars); + while(list($key,$val) = each($formvars)) { + if (is_array($val) || is_object($val)) { + while (list($cur_key, $cur_val) = each($val)) { + $postdata .= "--".$this->_mime_boundary."\r\n"; + $postdata .= "Content-Disposition: form-data; name=\"$key\[\]\"\r\n\r\n"; + $postdata .= "$cur_val\r\n"; + } + } else { + $postdata .= "--".$this->_mime_boundary."\r\n"; + $postdata .= "Content-Disposition: form-data; name=\"$key\"\r\n\r\n"; + $postdata .= "$val\r\n"; + } + } + + reset($formfiles); + while (list($field_name, $file_names) = each($formfiles)) { + settype($file_names, "array"); + while (list(, $file_name) = each($file_names)) { + if (!is_readable($file_name)) continue; + + $fp = fopen($file_name, "r"); + $file_content = fread($fp, filesize($file_name)); + fclose($fp); + $base_name = basename($file_name); + + $postdata .= "--".$this->_mime_boundary."\r\n"; + $postdata .= "Content-Disposition: form-data; name=\"$field_name\"; filename=\"$base_name\"\r\n\r\n"; + $postdata .= "$file_content\r\n"; + } + } + $postdata .= "--".$this->_mime_boundary."--\r\n"; + break; + } + + return $postdata; + } +} \ No newline at end of file diff --git a/lib/copy_this/misc/reqscraper/magpierss/rss_cache.inc b/lib/copy_this/misc/reqscraper/magpierss/rss_cache.inc new file mode 100644 index 000000000..7d9726f3b --- /dev/null +++ b/lib/copy_this/misc/reqscraper/magpierss/rss_cache.inc @@ -0,0 +1,198 @@ + + * Version: 0.51 + * License: GPL + * + * The lastest version of MagpieRSS can be obtained from: + * http://magpierss.sourceforge.net + * + * For questions, help, comments, discussion, etc., please join the + * Magpie mailing list: + * http://lists.sourceforge.net/lists/listinfo/magpierss-general + * + */ + +class RSSCache { + var $BASE_CACHE = './cache'; // where the cache files are stored + var $MAX_AGE = 3600; // when are files stale, default one hour + var $ERROR = ""; // accumulate error messages + + function RSSCache ($base='', $age='') { + if ( $base ) { + $this->BASE_CACHE = $base; + } + if ( $age ) { + $this->MAX_AGE = $age; + } + + // attempt to make the cache directory + if ( ! file_exists( $this->BASE_CACHE ) ) { + $status = @mkdir( $this->BASE_CACHE, 0755 ); + + // if make failed + if ( ! $status ) { + $this->error( + "Cache couldn't make dir '" . $this->BASE_CACHE . "'." + ); + } + } + } + +/*=======================================================================*\ + Function: set + Purpose: add an item to the cache, keyed on url + Input: url from wich the rss file was fetched + Output: true on sucess +\*=======================================================================*/ + function set ($url, $rss) { + $this->ERROR = ""; + $cache_file = $this->file_name( $url ); + $fp = @fopen( $cache_file, 'w' ); + + if ( ! $fp ) { + $this->error( + "Cache unable to open file for writing: $cache_file" + ); + return 0; + } + + + $data = $this->serialize( $rss ); + fwrite( $fp, $data ); + fclose( $fp ); + + return $cache_file; + } + +/*=======================================================================*\ + Function: get + Purpose: fetch an item from the cache + Input: url from wich the rss file was fetched + Output: cached object on HIT, false on MISS +\*=======================================================================*/ + function get ($url) { + $this->ERROR = ""; + $cache_file = $this->file_name( $url ); + + if ( ! file_exists( $cache_file ) ) { + $this->debug( + "Cache doesn't contain: $url (cache file: $cache_file)" + ); + return 0; + } + + $fp = @fopen($cache_file, 'r'); + if ( ! $fp ) { + $this->error( + "Failed to open cache file for reading: $cache_file" + ); + return 0; + } + + if ($filesize = filesize($cache_file) ) { + $data = fread( $fp, filesize($cache_file) ); + $rss = $this->unserialize( $data ); + + return $rss; + } + + return 0; + } + +/*=======================================================================*\ + Function: check_cache + Purpose: check a url for membership in the cache + and whether the object is older then MAX_AGE (ie. STALE) + Input: url from wich the rss file was fetched + Output: cached object on HIT, false on MISS +\*=======================================================================*/ + function check_cache ( $url ) { + $this->ERROR = ""; + $filename = $this->file_name( $url ); + + if ( file_exists( $filename ) ) { + // find how long ago the file was added to the cache + // and whether that is longer then MAX_AGE + $mtime = filemtime( $filename ); + $age = time() - $mtime; + if ( $this->MAX_AGE > $age ) { + // object exists and is current + return 'HIT'; + } + else { + // object exists but is old + return 'STALE'; + } + } + else { + // object does not exist + return 'MISS'; + } + } + + function cache_age( $cache_key ) { + $filename = $this->file_name( $url ); + if ( file_exists( $filename ) ) { + $mtime = filemtime( $filename ); + $age = time() - $mtime; + return $age; + } + else { + return -1; + } + } + +/*=======================================================================*\ + Function: serialize +\*=======================================================================*/ + function serialize ( $rss ) { + return serialize( $rss ); + } + +/*=======================================================================*\ + Function: unserialize +\*=======================================================================*/ + function unserialize ( $data ) { + return unserialize( $data ); + } + +/*=======================================================================*\ + Function: file_name + Purpose: map url to location in cache + Input: url from wich the rss file was fetched + Output: a file name +\*=======================================================================*/ + function file_name ($url) { + $filename = md5( $url ); + return join( DIRECTORY_SEPARATOR, array( $this->BASE_CACHE, $filename ) ); + } + +/*=======================================================================*\ + Function: error + Purpose: register error +\*=======================================================================*/ + function error ($errormsg, $lvl=E_USER_WARNING) { + // append PHP's error message if track_errors enabled + if ( isset($php_errormsg) ) { + $errormsg .= " ($php_errormsg)"; + } + $this->ERROR = $errormsg; + if ( MAGPIE_DEBUG ) { + trigger_error( $errormsg, $lvl); + } + else { + error_log( $errormsg, 0); + } + } + + function debug ($debugmsg, $lvl=E_USER_NOTICE) { + if ( MAGPIE_DEBUG ) { + $this->error("MagpieRSS [debug] $debugmsg", $lvl); + } + } + +} diff --git a/lib/copy_this/misc/reqscraper/magpierss/rss_fetch.inc b/lib/copy_this/misc/reqscraper/magpierss/rss_fetch.inc new file mode 100644 index 000000000..75d18126c --- /dev/null +++ b/lib/copy_this/misc/reqscraper/magpierss/rss_fetch.inc @@ -0,0 +1,456 @@ + + * License: GPL + * + * The lastest version of MagpieRSS can be obtained from: + * http://magpierss.sourceforge.net + * + * For questions, help, comments, discussion, etc., please join the + * Magpie mailing list: + * magpierss-general@lists.sourceforge.net + * + */ + +// Setup MAGPIE_DIR for use on hosts that don't include +// the current path in include_path. +// with thanks to rajiv and smarty +if (!defined('DIR_SEP')) { + define('DIR_SEP', DIRECTORY_SEPARATOR); +} + +if (!defined('MAGPIE_DIR')) { + define('MAGPIE_DIR', dirname(__FILE__) . DIR_SEP); +} + +require_once( MAGPIE_DIR . 'rss_parse.inc' ); +require_once( MAGPIE_DIR . 'rss_cache.inc' ); + +// for including 3rd party libraries +define('MAGPIE_EXTLIB', MAGPIE_DIR . 'extlib' . DIR_SEP); +require_once( MAGPIE_EXTLIB . 'Snoopy.class.inc'); + + +/* + * CONSTANTS - redefine these in your script to change the + * behaviour of fetch_rss() currently, most options effect the cache + * + * MAGPIE_CACHE_ON - Should Magpie cache parsed RSS objects? + * For me a built in cache was essential to creating a "PHP-like" + * feel to Magpie, see rss_cache.inc for rationale + * + * + * MAGPIE_CACHE_DIR - Where should Magpie cache parsed RSS objects? + * This should be a location that the webserver can write to. If this + * directory does not already exist Mapie will try to be smart and create + * it. This will often fail for permissions reasons. + * + * + * MAGPIE_CACHE_AGE - How long to store cached RSS objects? In seconds. + * + * + * MAGPIE_CACHE_FRESH_ONLY - If remote fetch fails, throw error + * instead of returning stale object? + * + * MAGPIE_DEBUG - Display debugging notices? + * +*/ + + +/*=======================================================================*\ + Function: fetch_rss: + Purpose: return RSS object for the give url + maintain the cache + Input: url of RSS file + Output: parsed RSS object (see rss_parse.inc) + + NOTES ON CACHEING: + If caching is on (MAGPIE_CACHE_ON) fetch_rss will first check the cache. + + NOTES ON RETRIEVING REMOTE FILES: + If conditional gets are on (MAGPIE_CONDITIONAL_GET_ON) fetch_rss will + return a cached object, and touch the cache object upon recieving a + 304. + + NOTES ON FAILED REQUESTS: + If there is an HTTP error while fetching an RSS object, the cached + version will be return, if it exists (and if MAGPIE_CACHE_FRESH_ONLY is off) +\*=======================================================================*/ + +define('MAGPIE_VERSION', '0.72'); + +$MAGPIE_ERROR = ""; + +function fetch_rss ($url) { + // initialize constants + init(); + + if ( !isset($url) ) { + error("fetch_rss called without a url"); + return false; + } + + // if cache is disabled + if ( !MAGPIE_CACHE_ON ) { + // fetch file, and parse it + $resp = _fetch_remote_file( $url ); + if ( is_success( $resp->status ) ) { + return _response_to_rss( $resp ); + } + else { + error("Failed to fetch $url and cache is off"); + return false; + } + } + // else cache is ON + else { + // Flow + // 1. check cache + // 2. if there is a hit, make sure its fresh + // 3. if cached obj fails freshness check, fetch remote + // 4. if remote fails, return stale object, or error + + $cache = new RSSCache( MAGPIE_CACHE_DIR, MAGPIE_CACHE_AGE ); + + if (MAGPIE_DEBUG and $cache->ERROR) { + debug($cache->ERROR, E_USER_WARNING); + } + + + $cache_status = 0; // response of check_cache + $request_headers = array(); // HTTP headers to send with fetch + $rss = 0; // parsed RSS object + $errormsg = 0; // errors, if any + + // store parsed XML by desired output encoding + // as character munging happens at parse time + $cache_key = $url . MAGPIE_OUTPUT_ENCODING; + + if (!$cache->ERROR) { + // return cache HIT, MISS, or STALE + $cache_status = $cache->check_cache( $cache_key); + } + + // if object cached, and cache is fresh, return cached obj + if ( $cache_status == 'HIT' ) { + $rss = $cache->get( $cache_key ); + if ( isset($rss) and $rss ) { + // should be cache age + $rss->from_cache = 1; + if ( MAGPIE_DEBUG > 1) { + debug("MagpieRSS: Cache HIT", E_USER_NOTICE); + } + return $rss; + } + } + + // else attempt a conditional get + + // setup headers + if ( $cache_status == 'STALE' ) { + $rss = $cache->get( $cache_key ); + if ( $rss and $rss->etag and $rss->last_modified ) { + $request_headers['If-None-Match'] = $rss->etag; + $request_headers['If-Last-Modified'] = $rss->last_modified; + } + } + + $resp = _fetch_remote_file( $url, $request_headers ); + + if (isset($resp) and $resp) { + if ($resp->status == '304' ) { + // we have the most current copy + if ( MAGPIE_DEBUG > 1) { + debug("Got 304 for $url"); + } + // reset cache on 304 (at minutillo insistent prodding) + $cache->set($cache_key, $rss); + return $rss; + } + elseif ( is_success( $resp->status ) ) { + $rss = _response_to_rss( $resp ); + if ( $rss ) { + if (MAGPIE_DEBUG > 1) { + debug("Fetch successful"); + } + // add object to cache + $cache->set( $cache_key, $rss ); + return $rss; + } + } + else { + $errormsg = "Failed to fetch $url "; + if ( $resp->status == '-100' ) { + $errormsg .= "(Request timed out after " . MAGPIE_FETCH_TIME_OUT . " seconds)"; + } + elseif ( $resp->error ) { + # compensate for Snoopy's annoying habbit to tacking + # on '\n' + $http_error = substr($resp->error, 0, -2); + $errormsg .= "(HTTP Error: $http_error)"; + } + else { + $errormsg .= "(HTTP Response: " . $resp->response_code .')'; + } + } + } + else { + $errormsg = "Unable to retrieve RSS file for unknown reasons."; + } + + // else fetch failed + + // attempt to return cached object + if ($rss) { + if ( MAGPIE_DEBUG ) { + debug("Returning STALE object for $url"); + } + return $rss; + } + + // else we totally failed + error( $errormsg ); + + return false; + + } // end if ( !MAGPIE_CACHE_ON ) { +} // end fetch_rss() + +/*=======================================================================*\ + Function: error + Purpose: set MAGPIE_ERROR, and trigger error +\*=======================================================================*/ + +function error ($errormsg, $lvl=E_USER_WARNING) { + global $MAGPIE_ERROR; + + // append PHP's error message if track_errors enabled + if ( isset($php_errormsg) ) { + $errormsg .= " ($php_errormsg)"; + } + if ( $errormsg ) { + $errormsg = "MagpieRSS: $errormsg"; + $MAGPIE_ERROR = $errormsg; + trigger_error( $errormsg, $lvl); + } +} + +function debug ($debugmsg, $lvl=E_USER_NOTICE) { + trigger_error("MagpieRSS [debug] $debugmsg", $lvl); +} + +/*=======================================================================*\ + Function: magpie_error + Purpose: accessor for the magpie error variable +\*=======================================================================*/ +function magpie_error ($errormsg="") { + global $MAGPIE_ERROR; + + if ( isset($errormsg) and $errormsg ) { + $MAGPIE_ERROR = $errormsg; + } + + return $MAGPIE_ERROR; +} + +/*=======================================================================*\ + Function: _fetch_remote_file + Purpose: retrieve an arbitrary remote file + Input: url of the remote file + headers to send along with the request (optional) + Output: an HTTP response object (see Snoopy.class.inc) +\*=======================================================================*/ +function _fetch_remote_file ($url, $headers = "" ) { + // Snoopy is an HTTP client in PHP + $client = new Snoopy(); + $client->agent = MAGPIE_USER_AGENT; + $client->read_timeout = MAGPIE_FETCH_TIME_OUT; + $client->use_gzip = MAGPIE_USE_GZIP; + if (is_array($headers) ) { + $client->rawheaders = $headers; + } + + @$client->fetch($url); + return $client; + +} + +/*=======================================================================*\ + Function: _response_to_rss + Purpose: parse an HTTP response object into an RSS object + Input: an HTTP response object (see Snoopy) + Output: parsed RSS object (see rss_parse) +\*=======================================================================*/ +function _response_to_rss ($resp) { + $rss = new MagpieRSS( $resp->results, MAGPIE_OUTPUT_ENCODING, MAGPIE_INPUT_ENCODING, MAGPIE_DETECT_ENCODING ); + + // if RSS parsed successfully + if ( $rss and !$rss->ERROR) { + + // find Etag, and Last-Modified + foreach($resp->headers as $h) { + // 2003-03-02 - Nicola Asuni (www.tecnick.com) - fixed bug "Undefined offset: 1" + if (strpos($h, ": ")) { + list($field, $val) = explode(": ", $h, 2); + } + else { + $field = $h; + $val = ""; + } + + if ( $field == 'ETag' ) { + $rss->etag = $val; + } + + if ( $field == 'Last-Modified' ) { + $rss->last_modified = $val; + } + } + + return $rss; + } // else construct error message + else { + $errormsg = "Failed to parse RSS file."; + + if ($rss) { + $errormsg .= " (" . $rss->ERROR . ")"; + } + error($errormsg); + + return false; + } // end if ($rss and !$rss->error) +} + +/*=======================================================================*\ + Function: init + Purpose: setup constants with default values + check for user overrides +\*=======================================================================*/ +function init () { + if ( defined('MAGPIE_INITALIZED') ) { + return; + } + else { + define('MAGPIE_INITALIZED', true); + } + + if ( !defined('MAGPIE_CACHE_ON') ) { + define('MAGPIE_CACHE_ON', true); + } + + if ( !defined('MAGPIE_CACHE_DIR') ) { + define('MAGPIE_CACHE_DIR', './cache'); + } + + if ( !defined('MAGPIE_CACHE_AGE') ) { + define('MAGPIE_CACHE_AGE', 60*60); // one hour + } + + if ( !defined('MAGPIE_CACHE_FRESH_ONLY') ) { + define('MAGPIE_CACHE_FRESH_ONLY', false); + } + + if ( !defined('MAGPIE_OUTPUT_ENCODING') ) { + define('MAGPIE_OUTPUT_ENCODING', 'ISO-8859-1'); + } + + if ( !defined('MAGPIE_INPUT_ENCODING') ) { + define('MAGPIE_INPUT_ENCODING', null); + } + + if ( !defined('MAGPIE_DETECT_ENCODING') ) { + define('MAGPIE_DETECT_ENCODING', true); + } + + if ( !defined('MAGPIE_DEBUG') ) { + define('MAGPIE_DEBUG', 0); + } + + if ( !defined('MAGPIE_USER_AGENT') ) { + $ua = 'MagpieRSS/'. MAGPIE_VERSION . ' (+http://magpierss.sf.net'; + + if ( MAGPIE_CACHE_ON ) { + $ua = $ua . ')'; + } + else { + $ua = $ua . '; No cache)'; + } + + define('MAGPIE_USER_AGENT', $ua); + } + + if ( !defined('MAGPIE_FETCH_TIME_OUT') ) { + define('MAGPIE_FETCH_TIME_OUT', 5); // 5 second timeout + } + + // use gzip encoding to fetch rss files if supported? + if ( !defined('MAGPIE_USE_GZIP') ) { + define('MAGPIE_USE_GZIP', true); + } +} + +// NOTE: the following code should really be in Snoopy, or at least +// somewhere other then rss_fetch! + +/*=======================================================================*\ + HTTP STATUS CODE PREDICATES + These functions attempt to classify an HTTP status code + based on RFC 2616 and RFC 2518. + + All of them take an HTTP status code as input, and return true or false + + All this code is adapted from LWP's HTTP::Status. +\*=======================================================================*/ + + +/*=======================================================================*\ + Function: is_info + Purpose: return true if Informational status code +\*=======================================================================*/ +function is_info ($sc) { + return $sc >= 100 && $sc < 200; +} + +/*=======================================================================*\ + Function: is_success + Purpose: return true if Successful status code +\*=======================================================================*/ +function is_success ($sc) { + return $sc >= 200 && $sc < 300; +} + +/*=======================================================================*\ + Function: is_redirect + Purpose: return true if Redirection status code +\*=======================================================================*/ +function is_redirect ($sc) { + return $sc >= 300 && $sc < 400; +} + +/*=======================================================================*\ + Function: is_error + Purpose: return true if Error status code +\*=======================================================================*/ +function is_error ($sc) { + return $sc >= 400 && $sc < 600; +} + +/*=======================================================================*\ + Function: is_client_error + Purpose: return true if Error status code, and its a client error +\*=======================================================================*/ +function is_client_error ($sc) { + return $sc >= 400 && $sc < 500; +} + +/*=======================================================================*\ + Function: is_client_error + Purpose: return true if Error status code, and its a server error +\*=======================================================================*/ +function is_server_error ($sc) { + return $sc >= 500 && $sc < 600; +} \ No newline at end of file diff --git a/lib/copy_this/misc/reqscraper/magpierss/rss_parse.inc b/lib/copy_this/misc/reqscraper/magpierss/rss_parse.inc new file mode 100644 index 000000000..63b30a21f --- /dev/null +++ b/lib/copy_this/misc/reqscraper/magpierss/rss_parse.inc @@ -0,0 +1,608 @@ + +* @version 0.7a +* @license GPL +* +*/ + +define('RSS', 'RSS'); +define('ATOM', 'Atom'); + +require_once (MAGPIE_DIR . 'rss_utils.inc'); + +/** +* Hybrid parser, and object, takes RSS as a string and returns a simple object. +* +* see: rss_fetch.inc for a simpler interface with integrated caching support +* +*/ +class MagpieRSS { + var $parser; + + var $current_item = array(); // item currently being parsed + var $items = array(); // collection of parsed items + var $channel = array(); // hash of channel fields + var $textinput = array(); + var $image = array(); + var $feed_type; + var $feed_version; + var $encoding = ''; // output encoding of parsed rss + + var $_source_encoding = ''; // only set if we have to parse xml prolog + + var $ERROR = ""; + var $WARNING = ""; + + // define some constants + + var $_CONTENT_CONSTRUCTS = array('content', 'summary', 'info', 'title', 'tagline', 'copyright'); + var $_KNOWN_ENCODINGS = array('UTF-8', 'US-ASCII', 'ISO-8859-1'); + + // parser variables, useless if you're not a parser, treat as private + var $stack = array(); // parser stack + var $inchannel = false; + var $initem = false; + var $incontent = false; // if in Atom field + var $intextinput = false; + var $inimage = false; + var $current_namespace = false; + + + /** + * Set up XML parser, parse source, and return populated RSS object.. + * + * @param string $source string containing the RSS to be parsed + * + * NOTE: Probably a good idea to leave the encoding options alone unless + * you know what you're doing as PHP's character set support is + * a little weird. + * + * NOTE: A lot of this is unnecessary but harmless with PHP5 + * + * + * @param string $output_encoding output the parsed RSS in this character + * set defaults to ISO-8859-1 as this is PHP's + * default. + * + * NOTE: might be changed to UTF-8 in future + * versions. + * + * @param string $input_encoding the character set of the incoming RSS source. + * Leave blank and Magpie will try to figure it + * out. + * + * + * @param bool $detect_encoding if false Magpie won't attempt to detect + * source encoding. (caveat emptor) + * + */ + function MagpieRSS ($source, $output_encoding='ISO-8859-1', + $input_encoding=null, $detect_encoding=true) + { + # if PHP xml isn't compiled in, die + # + if (!function_exists('xml_parser_create')) { + $this->error( "Failed to load PHP's XML Extension. " . + "http://www.php.net/manual/en/ref.xml.php", + E_USER_ERROR ); + } + + list($parser, $source) = $this->create_parser($source, + $output_encoding, $input_encoding, $detect_encoding); + + + if (!is_resource($parser)) { + $this->error( "Failed to create an instance of PHP's XML parser. " . + "http://www.php.net/manual/en/ref.xml.php", + E_USER_ERROR ); + } + + + $this->parser = $parser; + + # pass in parser, and a reference to this object + # setup handlers + # + xml_set_object( $this->parser, $this ); + xml_set_element_handler($this->parser, + 'feed_start_element', 'feed_end_element' ); + + xml_set_character_data_handler( $this->parser, 'feed_cdata' ); + + $status = xml_parse( $this->parser, $source ); + + if (! $status ) { + $errorcode = xml_get_error_code( $this->parser ); + if ( $errorcode != XML_ERROR_NONE ) { + $xml_error = xml_error_string( $errorcode ); + $error_line = xml_get_current_line_number($this->parser); + $error_col = xml_get_current_column_number($this->parser); + $errormsg = "$xml_error at line $error_line, column $error_col"; + + $this->error( $errormsg ); + } + } + + xml_parser_free( $this->parser ); + + $this->normalize(); + } + + function feed_start_element($p, $element, &$attrs) { + $el = $element = strtolower($element); + $attrs = array_change_key_case($attrs, CASE_LOWER); + + // check for a namespace, and split if found + $ns = false; + if ( strpos( $element, ':' ) ) { + list($ns, $el) = split( ':', $element, 2); + } + if ( $ns and $ns != 'rdf' ) { + $this->current_namespace = $ns; + } + + # if feed type isn't set, then this is first element of feed + # identify feed from root element + # + if (!isset($this->feed_type) ) { + if ( $el == 'rdf' ) { + $this->feed_type = RSS; + $this->feed_version = '1.0'; + } + elseif ( $el == 'rss' ) { + $this->feed_type = RSS; + $this->feed_version = $attrs['version']; + } + elseif ( $el == 'feed' ) { + $this->feed_type = ATOM; + $this->feed_version = $attrs['version']; + $this->inchannel = true; + } + return; + } + + if ( $el == 'channel' ) + { + $this->inchannel = true; + } + elseif ($el == 'attr') + { + if (isset($attrs['name']) && isset($attrs['value'])) + $this->append($attrs['name'], $attrs['value']); + } + elseif ($el == 'item' or $el == 'entry' ) + { + $this->initem = true; + if ( isset($attrs['rdf:about']) ) { + $this->current_item['about'] = $attrs['rdf:about']; + } + } + + // if we're in the default namespace of an RSS feed, + // record textinput or image fields + elseif ( + $this->feed_type == RSS and + $this->current_namespace == '' and + $el == 'textinput' ) + { + $this->intextinput = true; + } + + elseif ( + $this->feed_type == RSS and + $this->current_namespace == '' and + $el == 'image' ) + { + $this->inimage = true; + } + + # handle atom content constructs + elseif ( $this->feed_type == ATOM and in_array($el, $this->_CONTENT_CONSTRUCTS) ) + { + // avoid clashing w/ RSS mod_content + if ($el == 'content' ) { + $el = 'atom_content'; + } + + $this->incontent = $el; + + + } + + // if inside an Atom content construct (e.g. content or summary) field treat tags as text + elseif ($this->feed_type == ATOM and $this->incontent ) + { + // if tags are inlined, then flatten + $attrs_str = join(' ', + array_map('map_attrs', + array_keys($attrs), + array_values($attrs) ) ); + + $this->append_content( "<$element $attrs_str>" ); + + array_unshift( $this->stack, $el ); + } + + // Atom support many links per containging element. + // Magpie treats link elements of type rel='alternate' + // as being equivalent to RSS's simple link element. + // + elseif ($this->feed_type == ATOM and $el == 'link' ) + { + if ( isset($attrs['rel']) and $attrs['rel'] == 'alternate' ) + { + $link_el = 'link'; + } + else { + $link_el = 'link_' . $attrs['rel']; + } + + $this->append($link_el, $attrs['href']); + } + // set stack[0] to current element + else { + array_unshift($this->stack, $el); + } + } + + + + function feed_cdata ($p, $text) { + if ($this->feed_type == ATOM and $this->incontent) + { + $this->append_content( $text ); + } + else { + $current_el = join('_', array_reverse($this->stack)); + $this->append($current_el, $text); + } + } + + function feed_end_element ($p, $el) { + $el = strtolower($el); + + if ( $el == 'item' or $el == 'entry' ) + { + $this->items[] = $this->current_item; + $this->current_item = array(); + $this->initem = false; + } + elseif ($this->feed_type == RSS and $this->current_namespace == '' and $el == 'textinput' ) + { + $this->intextinput = false; + } + elseif ($this->feed_type == RSS and $this->current_namespace == '' and $el == 'image' ) + { + $this->inimage = false; + } + elseif ($this->feed_type == ATOM and in_array($el, $this->_CONTENT_CONSTRUCTS) ) + { + $this->incontent = false; + } + elseif ($el == 'channel' or $el == 'feed' ) + { + $this->inchannel = false; + } + elseif ($this->feed_type == ATOM and $this->incontent ) { + // balance tags properly + // note: i don't think this is actually neccessary + if ( $this->stack[0] == $el ) + { + $this->append_content(""); + } + else { + $this->append_content("<$el />"); + } + + array_shift( $this->stack ); + } + else { + array_shift( $this->stack ); + } + + $this->current_namespace = false; + } + + function concat (&$str1, $str2="") { + if (!isset($str1) ) { + $str1=""; + } + $str1 .= $str2; + } + + + + function append_content($text) { + if ( $this->initem ) { + $this->concat( $this->current_item[ $this->incontent ], $text ); + } + elseif ( $this->inchannel ) { + $this->concat( $this->channel[ $this->incontent ], $text ); + } + } + + // smart append - field and namespace aware + function append($el, $text) { + if (!$el) { + return; + } + if ( $this->current_namespace ) + { + if ( $this->initem ) { + $this->concat( + $this->current_item[ $this->current_namespace ][ $el ], $text); + } + elseif ($this->inchannel) { + $this->concat( + $this->channel[ $this->current_namespace][ $el ], $text ); + } + elseif ($this->intextinput) { + $this->concat( + $this->textinput[ $this->current_namespace][ $el ], $text ); + } + elseif ($this->inimage) { + $this->concat( + $this->image[ $this->current_namespace ][ $el ], $text ); + } + } + else { + if ( $this->initem ) { + $this->concat( + $this->current_item[ $el ], $text); + } + elseif ($this->intextinput) { + $this->concat( + $this->textinput[ $el ], $text ); + } + elseif ($this->inimage) { + $this->concat( + $this->image[ $el ], $text ); + } + elseif ($this->inchannel) { + $this->concat( + $this->channel[ $el ], $text ); + } + + } + } + + function normalize () { + // if atom populate rss fields + if ( $this->is_atom() ) { + $this->channel['description'] = $this->channel['tagline']; + for ( $i = 0; $i < count($this->items); $i++) { + $item = $this->items[$i]; + if ( isset($item['summary']) ) + $item['description'] = $item['summary']; + if ( isset($item['atom_content'])) + $item['content']['encoded'] = $item['atom_content']; + + $atom_date = (isset($item['issued']) ) ? $item['issued'] : $item['modified']; + if ( $atom_date ) { + $epoch = @parse_w3cdtf($atom_date); + if ($epoch and $epoch > 0) { + $item['date_timestamp'] = $epoch; + } + } + + $this->items[$i] = $item; + } + } + elseif ( $this->is_rss() ) { + $this->channel['tagline'] = $this->channel['description']; + for ( $i = 0; $i < count($this->items); $i++) { + $item = $this->items[$i]; + if ( isset($item['description'])) + $item['summary'] = $item['description']; + if ( isset($item['content']['encoded'] ) ) + $item['atom_content'] = $item['content']['encoded']; + + if ( $this->is_rss() == '1.0' and isset($item['dc']['date']) ) { + $epoch = @parse_w3cdtf($item['dc']['date']); + if ($epoch and $epoch > 0) { + $item['date_timestamp'] = $epoch; + } + } + elseif ( isset($item['pubdate']) ) { + $epoch = @strtotime($item['pubdate']); + if ($epoch > 0) { + $item['date_timestamp'] = $epoch; + } + } + + $this->items[$i] = $item; + } + } + } + + + function is_rss () { + if ( $this->feed_type == RSS ) { + return $this->feed_version; + } + else { + return false; + } + } + + function is_atom() { + if ( $this->feed_type == ATOM ) { + return $this->feed_version; + } + else { + return false; + } + } + + /** + * return XML parser, and possibly re-encoded source + * + */ + function create_parser($source, $out_enc, $in_enc, $detect) { + if ( substr(phpversion(),0,1) == 5) { + $parser = $this->php5_create_parser($in_enc, $detect); + } + else { + list($parser, $source) = $this->php4_create_parser($source, $in_enc, $detect); + } + if ($out_enc) { + $this->encoding = $out_enc; + xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $out_enc); + } + + return array($parser, $source); + } + + /** + * Instantiate an XML parser under PHP5 + * + * PHP5 will do a fine job of detecting input encoding + * if passed an empty string as the encoding. + * + * All hail libxml2! + * + */ + function php5_create_parser($in_enc, $detect) { + // by default php5 does a fine job of detecting input encodings + if(!$detect && $in_enc) { + return xml_parser_create($in_enc); + } + else { + return xml_parser_create(''); + } + } + + /** + * Instaniate an XML parser under PHP4 + * + * Unfortunately PHP4's support for character encodings + * and especially XML and character encodings sucks. As + * long as the documents you parse only contain characters + * from the ISO-8859-1 character set (a superset of ASCII, + * and a subset of UTF-8) you're fine. However once you + * step out of that comfy little world things get mad, bad, + * and dangerous to know. + * + * The following code is based on SJM's work with FoF + * @see http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss + * + */ + function php4_create_parser($source, $in_enc, $detect) { + if ( !$detect ) { + return array(xml_parser_create($in_enc), $source); + } + + if (!$in_enc) { + if (preg_match('//m', $source, $m)) { + $in_enc = strtoupper($m[1]); + $this->source_encoding = $in_enc; + } + else { + $in_enc = 'UTF-8'; + } + } + + if ($this->known_encoding($in_enc)) { + return array(xml_parser_create($in_enc), $source); + } + + // the dectected encoding is not one of the simple encodings PHP knows + + // attempt to use the iconv extension to + // cast the XML to a known encoding + // @see http://php.net/iconv + + if (function_exists('iconv')) { + $encoded_source = iconv($in_enc,'UTF-8', $source); + if ($encoded_source) { + return array(xml_parser_create('UTF-8'), $encoded_source); + } + } + + // iconv didn't work, try mb_convert_encoding + // @see http://php.net/mbstring + if(function_exists('mb_convert_encoding')) { + $encoded_source = mb_convert_encoding($source, 'UTF-8', $in_enc ); + if ($encoded_source) { + return array(xml_parser_create('UTF-8'), $encoded_source); + } + } + + // else + $this->error("Feed is in an unsupported character encoding. ($in_enc) " . + "You may see strange artifacts, and mangled characters.", + E_USER_NOTICE); + + return array(xml_parser_create(), $source); + } + + function known_encoding($enc) { + $enc = strtoupper($enc); + if ( in_array($enc, $this->_KNOWN_ENCODINGS) ) { + return $enc; + } + else { + return false; + } + } + + function error ($errormsg, $lvl=E_USER_WARNING) { + // append PHP's error message if track_errors enabled + if ( isset($php_errormsg) ) { + $errormsg .= " ($php_errormsg)"; + } + if ( MAGPIE_DEBUG ) { + trigger_error( $errormsg, $lvl); + } + else { + error_log( $errormsg, 0); + } + + $notices = E_USER_NOTICE|E_NOTICE; + if ( $lvl&$notices ) { + $this->WARNING = $errormsg; + } else { + $this->ERROR = $errormsg; + } + } + + +} // end class RSS + +function map_attrs($k, $v) { + return "$k=\"$v\""; +} + +// patch to support medieval versions of PHP4.1.x, +// courtesy, Ryan Currie, ryan@digibliss.com + +if (!function_exists('array_change_key_case')) { + define("CASE_UPPER",1); + define("CASE_LOWER",0); + + + function array_change_key_case($array,$case=CASE_LOWER) { + if ($case=CASE_LOWER) $cmd=strtolower; + elseif ($case=CASE_UPPER) $cmd=strtoupper; + foreach($array as $key=>$value) { + $output[$cmd($key)]=$value; + } + return $output; + } + +} diff --git a/lib/copy_this/misc/reqscraper/magpierss/rss_utils.inc b/lib/copy_this/misc/reqscraper/magpierss/rss_utils.inc new file mode 100644 index 000000000..3900a9554 --- /dev/null +++ b/lib/copy_this/misc/reqscraper/magpierss/rss_utils.inc @@ -0,0 +1,65 @@ + + * Version: 0.51 + * License: GPL + * + * The lastest version of MagpieRSS can be obtained from: + * http://magpierss.sourceforge.net + * + * For questions, help, comments, discussion, etc., please join the + * Magpie mailing list: + * magpierss-general@lists.sourceforge.net + */ + + +/*======================================================================*\ + Function: parse_w3cdtf + Purpose: parse a W3CDTF date into unix epoch + + NOTE: http://www.w3.org/TR/NOTE-datetime +\*======================================================================*/ + +function parse_w3cdtf ( $date_str ) { + + # regex to match wc3dtf + $pat = "/(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(:(\d{2}))?(?:([-+])(\d{2}):?(\d{2})|(Z))?/"; + + if ( preg_match( $pat, $date_str, $match ) ) { + list( $year, $month, $day, $hours, $minutes, $seconds) = + array( $match[1], $match[2], $match[3], $match[4], $match[5], $match[6]); + + # calc epoch for current date assuming GMT + $epoch = gmmktime( $hours, $minutes, $seconds, $month, $day, $year); + + $offset = 0; + if ( $match[10] == 'Z' ) { + # zulu time, aka GMT + } + else { + list( $tz_mod, $tz_hour, $tz_min ) = + array( $match[8], $match[9], $match[10]); + + # zero out the variables + if ( ! $tz_hour ) { $tz_hour = 0; } + if ( ! $tz_min ) { $tz_min = 0; } + + $offset_secs = (($tz_hour*60)+$tz_min)*60; + + # is timezone ahead of GMT? then subtract offset + # + if ( $tz_mod == '+' ) { + $offset_secs = $offset_secs * -1; + } + + $offset = $offset_secs; + } + $epoch = $epoch + $offset; + return $epoch; + } + else { + return -1; + } +} \ No newline at end of file diff --git a/lib/copy_this/misc/reqscraper/query.php b/lib/copy_this/misc/reqscraper/query.php new file mode 100644 index 000000000..de5b39f93 --- /dev/null +++ b/lib/copy_this/misc/reqscraper/query.php @@ -0,0 +1,81 @@ +"; +while ($row = mysql_fetch_assoc($result)) + $ret.="\n"; +$ret.=""; + +// +// output xml +// +header("Content-type: text/xml"); +echo "\n"; +echo $ret; +die(); + + +function cleanXML($strin) +{ + $strout = null; + + for ($i = 0; $i < strlen($strin); $i++) + { + $ord = ord($strin[$i]); + + if (($ord > 0 && $ord < 32) || ($ord >= 127)) + { + $strout .= "&#{$ord};"; + } + else + { + switch ($strin[$i]) + { + case '<': + $strout .= '<'; + break; + case '>': + $strout .= '>'; + break; + case '&': + $strout .= '&'; + break; + case '"': + $strout .= '"'; + break; + default: + $strout .= $strin[$i]; + } + } + } + + return $strout; +} \ No newline at end of file diff --git a/lib/copy_this/misc/reqscraper/rss.php b/lib/copy_this/misc/reqscraper/rss.php new file mode 100644 index 000000000..ee79f83ce --- /dev/null +++ b/lib/copy_this/misc/reqscraper/rss.php @@ -0,0 +1,76 @@ + 100 || !is_numeric($limit)) $limit = 100; + +if ($type == "") +{ + header("Content-type: text/xml"); + echo "\n"; + echo "no group specified\n"; + die(); +} + +if ($type != "g") +{ + $result = mysql_query("select ID from feed where '".mysql_real_escape_string($type)."' REGEXP code"); + $feedid = -1; + while ($row = mysql_fetch_assoc($result)) + $feedid = $row["ID"]; + + $result = mysql_query("select item.*, feed.* from item join ( select ID from item where feedID = '".mysql_real_escape_string($feedid)."' order by adddateunique desc limit ".$limit." ) x on x.ID = item.ID inner join feed on feed.ID = item.feedID inner join access on access.guid = '".mysql_real_escape_string($uid)."' order by item.id desc"); +} +else + $result = mysql_query("select item.*, feed.* from item join ( select item.ID from item inner join access on access.guid = '".mysql_real_escape_string($uid)."' and item.feedid != coalesce(access.misc, -1) and role=2 where feedid in (select id from feed where name = 'gid') ORDER BY item.adddateunique DESC LIMIT ".$limit." ) x on x.ID = item.ID inner join feed on feed.ID = item.feedID order by item.ID desc"); + +if (!$result) +{ + header("Content-type: text/xml"); + echo "\n"; + echo "general error"; + die(); +} + +// +// build metadata about the item(s) +// +$xml = ""; +while ($row = mysql_fetch_assoc($result)) +{ + //create the xml + $xml .= "\t\n"; + $xml .= "\t\t".htmlentities($row['title'])."\n"; + $xml .= "\t\t".date('r', strtotime($row['adddate']))."\n"; + $xml .= "\t\t".htmlentities($row['reqid'])."\n"; + $xml .= "\t\t".htmlentities($row['code'])."\n"; + $xml .= "\t\t".htmlentities($row['link'])."\n"; + if ($row['description']!= "") + $xml .= "\t\t\n"; + $xml .= "\t\t".htmlentities($row['guid'])."\n"; + $xml .= "\t\n"; +} + +// +// build the xml +// +$xmlstart = " + + +".mysql_real_escape_string(htmlentities($type))." feed +http://www.newznab.com +".mysql_real_escape_string(htmlentities($type))." feed +en-us\n"; + +$xmlend = "\n"; + +$ret = $xmlstart . $xml . $xmlend; + +// +// output xml +// +header("Content-type: text/xml"); +echo "\n"; +echo $ret; \ No newline at end of file diff --git a/lib/copy_this/misc/reqscraper/schema.sql b/lib/copy_this/misc/reqscraper/schema.sql new file mode 100644 index 000000000..afa33bac9 --- /dev/null +++ b/lib/copy_this/misc/reqscraper/schema.sql @@ -0,0 +1,68 @@ + +DROP TABLE IF EXISTS `feed`; +CREATE TABLE `feed` +( + `ID` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, + `code` VARCHAR(50) NULL, + `name` VARCHAR(255) NULL, + `url` VARCHAR(1000) NOT NULL, + `reqidcol` VARCHAR(255) NULL, + `reqidregex` VARCHAR(2000) NOT NULL, + `titlecol` VARCHAR(255) NULL, + `titleregex` VARCHAR(2000) NOT NULL, + `lastupdate` DATETIME NULL, + `updatemins` TINYINT(3) NOT NULL DEFAULT '55', + `status` INT NOT NULL DEFAULT 1, + PRIMARY KEY (`ID`) +) ENGINE=MYISAM AUTO_INCREMENT=1 ; + +CREATE INDEX ix_feed_code ON feed (CODE); + +INSERT INTO feed (CODE, NAME, url, titlecol, titleregex, reqidcol, reqidregex, lastupdate) VALUES ('alt.binaries.teevee', 'abteevee', 'http://abteevee.allfilled.com/rss.php', 'title', '/(?P.*)/i', 'description', '/^ReqId: (?P<reqid>\\d{3,6})/i', NULL); +INSERT INTO feed (CODE, NAME, url, titlecol, titleregex, reqidcol, reqidregex, lastupdate) VALUES ('alt.binaries.erotica', 'aberotica', 'http://aberotica.allfilled.com/rss.php', 'title', '/(?P<title>.*)/i', 'description', '/^ReqId: (?P<reqid>\\d{3,6})/i', NULL); +INSERT INTO feed (CODE, NAME, url, titlecol, titleregex, reqidcol, reqidregex, lastupdate) VALUES ('alt.binaries.games.wii', 'abgwii', 'http://www.abgx.net/rss/abgw/posted.rss', 'title', '/^Req\\s\\d{1,6}\\s\\-\\s(?P<title>.\\S*)/i', 'title', '/^Req (?P<reqid>\\d{3,6})/i', NULL); +INSERT INTO feed (CODE, NAME, url, titlecol, titleregex, reqidcol, reqidregex, lastupdate) VALUES ('alt.binaries.games.xbox360', 'abg360', 'http://www.abgx.net/rss/x360/posted.rss', 'title', '/^Req\\s\\d{1,6}\\s\\-\\s(?P<title>.\\S*)/i', 'title', '/^Req (?P<reqid>\\d{3,6})/i', NULL); +INSERT INTO feed (CODE, NAME, url, titlecol, titleregex, reqidcol, reqidregex, lastupdate) VALUES ('alt.binaries.console.ps3', 'ps3', 'http://www.abgx.net/rss/abcp/posted.rss', 'title', '/^Req\\s\\d{1,6}\\s\\-\\s(?P<title>.\\S*)/i', 'title', '/^Req (?P<reqid>\\d{3,6})/i', NULL); +INSERT INTO feed (CODE, NAME, url, titlecol, titleregex, reqidcol, reqidregex, lastupdate) VALUES ('alt.binaries.sony.psp', 'psp', 'http://www.abgx.net/rss/absp/posted.rss', 'title', '/^Req\\s\\d{1,6}\\s\\-\\s(?P<title>.\\S*)/i', 'title', '/^Req (?P<reqid>\\d{3,6})/i', NULL); +INSERT INTO feed (CODE, NAME, url, titlecol, titleregex, reqidcol, reqidregex, lastupdate) VALUES ('alt.binaries.games.nintendods', 'nds', 'http://www.abgx.net/rss/abgn/posted.rss', 'title', '/^Req\\s\\d{1,6}\\s\\-\\s(?P<title>.\\S*)/i', 'title', '/^Req (?P<reqid>\\d{3,6})/i', NULL); +INSERT INTO feed (CODE, NAME, url, titlecol, titleregex, reqidcol, reqidregex, lastupdate) VALUES ('alt.binaries.inner-sanctum', 'innersanct', 'http://rss.omgwtfnzbs.org/rss-info.php', 'title', '/^(?P<title>.*)$/i', '', '-1', NULL); +INSERT INTO feed (CODE, NAME, url, titlecol, titleregex, reqidcol, reqidregex, lastupdate) VALUES ('alt.binaries.moovee', 'abmoovee', 'http://abmoovee.allfilled.com/rss.php', 'title', '/(?P<title>.*)/i', 'description', '/^ReqId: (?P<reqid>\\d{3,6})/i', NULL); +INSERT INTO feed (CODE, NAME, url, titlecol, titleregex, reqidcol, reqidregex, lastupdate) VALUES ('alt.binaries.srrdb', 'srrdb', 'http://www.srrdb.com/feed/srrs', 'title', '/(?P<title>.*)/i', 'description', '/Archived files.*<td>(?P<reqid>.*?\\.(avi|mkv|mp4|mov|wmv|iso|img|mp3|m3u|gcm|ps3|wad|ac3|nds|bin|mdf))<\\/td>/ims', null); + + + +DROP TABLE IF EXISTS `item`; +CREATE TABLE `item` +( + `ID` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, + `feedID` INT NOT NULL, + `reqid` VARCHAR(255) NOT NULL, + `title` VARCHAR(255) NULL, + `link` VARCHAR(1000) NULL, + `description` VARCHAR(1000) NULL, + `pubdate` DATETIME NOT NULL, + `guid` VARCHAR(1000) NULL, + `adddate` DATETIME NOT NULL, + `adddateunique` BIGINT UNSIGNED NOT NULL, + PRIMARY KEY (`ID`) +) ENGINE=MYISAM AUTO_INCREMENT=1 ; + +CREATE INDEX ix_item_feedID ON item (feedID); +CREATE INDEX ix_item_reqid ON item (reqid); +CREATE UNIQUE INDEX ix_reqid_title ON item (reqid, title); +CREATE UNIQUE INDEX ix_feedid_reqid ON item (feedID, reqid); +CREATE INDEX ix_item_adddateunique ON item (adddateunique); + + +DROP TABLE IF EXISTS `access`; +CREATE TABLE `access` +( + `ID` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, + `guid` VARCHAR(40) NOT NULL, + `role` INT NOT NULL, + `description` VARCHAR(1000) NULL, + `misc` VARCHAR(1000) NULL, + PRIMARY KEY (`ID`) +) ENGINE=MYISAM AUTO_INCREMENT=1 ; + +CREATE INDEX ix_access_guid ON access (guid); \ No newline at end of file diff --git a/lib/copy_this/misc/reqscraper/scrape.php b/lib/copy_this/misc/reqscraper/scrape.php new file mode 100644 index 000000000..cb600f457 --- /dev/null +++ b/lib/copy_this/misc/reqscraper/scrape.php @@ -0,0 +1,95 @@ +<?php + +require_once('magpierss/rss_fetch.inc'); +require_once('config.php'); + +// +// retrieve a list of feeds to be scraped +// +$result = mysql_query("SELECT *, NOW() as now FROM feed WHERE status=1"); +while ($row = mysql_fetch_assoc($result)) +{ + + if (strtotime($row['now']) - strtotime($row['lastupdate']) < $row['updatemins']*60) { + continue; + } + + echo "checking ".$row["code"]."\n"; + $rss = fetch_rss($row["url"]); + + $upd = mysql_query("UPDATE feed SET lastupdate = NOW() WHERE ID = ".$row['ID']); + + // + // scrape every item into a database table + // + foreach ($rss->items as $item) + { + $link = ""; + if (isset($item['link'])) + $link = mysql_real_escape_string($item['link']); + + if (isset($item['description'])) + $description = mysql_real_escape_string($item['description']); + elseif (isset($item['summary'])) + $description = mysql_real_escape_string($item['description']); + else + $description = ""; + + $feedID = $row["ID"]; + + if (isset($item['pubdate'])) + $pubdate = date("Y-m-d H:i:s", strtotime($item['pubdate'])); + elseif (isset($item["dc"]) && isset($item["dc"]["date"])) + $pubdate = date("Y-m-d H:i:s", strtotime($item["dc"]["date"])); + else + $pubdate = date("Y-m-d H:i:s"); + + // + // store 'specific stuff' like parsed reqids by regexing + // + $reqid = 0; + $matches = ""; + + $title = ""; + if (preg_match($row["titleregex"], $item[$row["titlecol"]], $matches)) + $title = mysql_real_escape_string($matches["title"]); + + //straight md5 + if ($row["reqidregex"] == "-1" && $title != "") + { + $reqid = md5($title); + } + //regex reqid out of columns + else + { + //multi dimensional position + $multi = strpos($row["reqidcol"], ':'); + if ($multi !== FALSE) + { + $part1 = substr($row["reqidcol"], 0, $multi); + $part2 = substr($row["reqidcol"], $multi + 1); + + if (preg_match($row["reqidregex"], $item[$part1][$part2], $matches)) + $reqid = mysql_real_escape_string($matches["reqid"]); + } + else + { + if (preg_match($row["reqidregex"], $item[$row["reqidcol"]], $matches)) + $reqid = mysql_real_escape_string($matches["reqid"]); + } + } + + if (isset($item['guid'])) + $guid = mysql_real_escape_string($item['guid']); + else + { + if ($title != "" && $reqid != 0) + $guid = md5($reqid.$title); + else + $guid = md5(uniqid()); + } + + $addateunique = round(microtime(true) * 1000); + $res = mysql_query("INSERT INTO item (feedID, reqid, title, link, description, pubdate, guid, adddate, adddateunique) VALUES ($feedID, '$reqid', '$title', '$link', '$description', '$pubdate', '$guid', NOW(), '$addateunique') ON DUPLICATE KEY update reqid = '$reqid', title = '$title'"); + } +} \ No newline at end of file diff --git a/lib/copy_this/misc/reqscraper/update.sql b/lib/copy_this/misc/reqscraper/update.sql new file mode 100644 index 000000000..b0fb62f16 --- /dev/null +++ b/lib/copy_this/misc/reqscraper/update.sql @@ -0,0 +1,5 @@ +ALTER TABLE `feed` ADD `updatemins` TINYINT( 3 ) NOT NULL DEFAULT '55' AFTER `titleregex`; + +ALTER TABLE `item` ADD UNIQUE `ix_reqid_title` ( `reqid` , `title` ); + +ALTER TABLE `item` DROP INDEX `ix_item_guid`; \ No newline at end of file diff --git a/lib/copy_this/misc/sphinxsearch/create_se_tables.php b/lib/copy_this/misc/sphinxsearch/create_se_tables.php index d3871963a..0a567cfd1 100644 --- a/lib/copy_this/misc/sphinxsearch/create_se_tables.php +++ b/lib/copy_this/misc/sphinxsearch/create_se_tables.php @@ -1,7 +1,8 @@ <?php require dirname(__FILE__) . '/../../www/config.php'; -require_once (NN_LIB . 'framework' . DS . 'db.php'); -require_once (NN_LIB . 'ReleaseSearch.php'); + +use newznab\db\DB; + if (NN_RELEASE_SEARCH_TYPE != \ReleaseSearch::SPHINX) { exit('Error, NN_RELEASE_SEARCH_TYPE in www/settings.php must be set to SPHINX!' . PHP_EOL); @@ -37,4 +38,4 @@ foreach ($tables as $table => $query) { $pdo->queryExec($query); } -echo 'All done! If you messed up your sphinx connection info, you can rerun this script.' . PHP_EOL; +echo 'All done! If you messed up your sphinx connection info, you can rerun this script.' . PHP_EOL; \ No newline at end of file diff --git a/lib/copy_this/misc/sphinxsearch/optimize.php b/lib/copy_this/misc/sphinxsearch/optimize.php index 06f773807..5fa12ef10 100644 --- a/lib/copy_this/misc/sphinxsearch/optimize.php +++ b/lib/copy_this/misc/sphinxsearch/optimize.php @@ -1,6 +1,5 @@ <?php require dirname(__FILE__) . '/../../www/config.php'; -require_once (NN_LIB . 'SphinxSearch.php'); if (!isset($argv[1]) || !in_array($argv[1], ['releases_rt'])) { exit('Argument1 is the index name, currently only releases_rt is supported.' . PHP_EOL); diff --git a/lib/copy_this/misc/sphinxsearch/populate_rt_indexes.php b/lib/copy_this/misc/sphinxsearch/populate_rt_indexes.php index 85f94e707..014d1dac5 100644 --- a/lib/copy_this/misc/sphinxsearch/populate_rt_indexes.php +++ b/lib/copy_this/misc/sphinxsearch/populate_rt_indexes.php @@ -1,8 +1,7 @@ <?php require dirname(__FILE__) . '/../../www/config.php'; -require_once (NN_LIB . 'framework' . DS . 'db.php'); -require_once (NN_LIB . 'ReleaseSearch.php'); -require_once (NN_LIB . 'SphinxSearch.php'); + +use newznab\db\DB; if (NN_RELEASE_SEARCH_TYPE != \ReleaseSearch::SPHINX) { exit('Error, NN_RELEASE_SEARCH_TYPE in www/settings.php must be set to SPHINX!' . PHP_EOL); @@ -23,7 +22,7 @@ switch ($argv[1]) { // Bulk insert releases into sphinx RT index. function releases_rt() { - $pdo = new \DB(); + $pdo = new DB(); $rows = $pdo->queryExec('SELECT id, guid, name, searchname, fromname FROM releases'); if ($rows !== false && $rows->rowCount()) { @@ -56,4 +55,4 @@ function releases_rt() } else { echo 'No releases in your DB or an error occurred. This will need to be resolved before you can use the search.' . PHP_EOL; } -} +} \ No newline at end of file diff --git a/lib/copy_this/misc/sphinxsearch/toggle_search_type.php b/lib/copy_this/misc/sphinxsearch/toggle_search_type.php index 17ed8f767..e5c7168d3 100644 --- a/lib/copy_this/misc/sphinxsearch/toggle_search_type.php +++ b/lib/copy_this/misc/sphinxsearch/toggle_search_type.php @@ -1,7 +1,7 @@ <?php require_once dirname(__FILE__) . '/../../www/config.php'; -require_once (NN_LIB . 'framework' . DS . 'db.php'); -require_once (NN_LIB . 'ReleaseSearch.php'); + +use newznab\db\DB; if (!isset($argv[1]) || !in_array($argv[1], ['sphinx', 'standard'])) { @@ -14,13 +14,13 @@ if (!isset($argv[1]) || !in_array($argv[1], ['sphinx', 'standard'])) { switch ($argv[1]) { case 'sphinx': if (NN_RELEASE_SEARCH_TYPE == \ReleaseSearch::SPHINX) { - optimizeForSphinx(new \DB()); + optimizeForSphinx(new DB()); } else { echo PHP_EOL . $pdo->log->error('Error, NN_RELEASE_SEARCH_TYPE in www/settings.php must be set to SPHINX to optimize for Sphinx!' . PHP_EOL); } break; case 'standard': - revertToStandard(new \DB()); + revertToStandard(new DB()); break; } @@ -134,4 +134,4 @@ function dropSearchTriggers($pdo) $pdo->queryExec('DROP TRIGGER IF EXISTS insert_search'); $pdo->queryExec('DROP TRIGGER IF EXISTS update_search'); $pdo->queryExec('DROP TRIGGER IF EXISTS delete_search'); -} +} \ No newline at end of file diff --git a/lib/copy_this/misc/testing/checkblanklinenzbs.php b/lib/copy_this/misc/testing/checkblanklinenzbs.php new file mode 100644 index 000000000..ae71f0771 --- /dev/null +++ b/lib/copy_this/misc/testing/checkblanklinenzbs.php @@ -0,0 +1,25 @@ +<?php +define('FS_ROOT', realpath(dirname(__FILE__))); + +use newznab\db\DB; + + +$db = new DB(); +$n = new Nzb(); +$s = New Sites; +$site = $s->get(); + +$items = $db->query("SELECT guid FROM releases"); + +while ($item = array_pop($items)) +{ + $guid = $item['guid']; + $nzbpath = $n->getNZBPath($guid, $site->nzbpath); + $zd = _gzopen($nzbpath, "r"); + $s = gzread($zd, 10 ); + + if ($s != "<?xml vers") + { + echo "fucked - ". $guid . "\n"; + } +} \ No newline at end of file diff --git a/lib/copy_this/misc/testing/deletepreviews.php b/lib/copy_this/misc/testing/deletepreviews.php new file mode 100644 index 000000000..862aecf64 --- /dev/null +++ b/lib/copy_this/misc/testing/deletepreviews.php @@ -0,0 +1,23 @@ +<?php + +//This script allows you to delete properly all preview images for a range + +define('FS_ROOT', realpath(dirname(__FILE__))); + +use newznab\db\DB; + +$releases = new Releases(); +$db = new DB; + +// +// delete all previews over a year old +// +$sql = "select guid from releases where adddate < date_sub(now(), interval 365 day) and haspreview = 1;"; + +$rel = $db->query($sql); +echo "about to delete ".count($rel)." release previews"; + +foreach ($rel as $r) +{ + $releases->deletePreview($r['guid']); +} \ No newline at end of file diff --git a/lib/copy_this/misc/testing/deletereleases.php b/lib/copy_this/misc/testing/deletereleases.php new file mode 100644 index 000000000..41ad9d4ec --- /dev/null +++ b/lib/copy_this/misc/testing/deletereleases.php @@ -0,0 +1,75 @@ +<?php + +//This script allows you to delete properly all releases which match some criteria +//The nzb, covers and all linked records will be deleted properly. + +define('FS_ROOT', realpath(dirname(__FILE__))); + +use newznab\db\DB; + +$releases = new Releases(); +$db = new DB(); + +// +// [1] delete all releases for a group which only has x number of files +// +//$sql = "select * from releases where totalpart = 1 and groupID in (select ID from groups where name = 'alt.binaries.cd.image')"; + + +// +// [2] delete all releases where the only file inside the rars is *.exe and they are not in the PC category +// +/* +$sql = " +select releasefiles.releaseID as ID +from releasefiles +inner join +( select releaseID, count(*) as totnum from releasefiles group by releaseID ) x on x.releaseID = releasefiles.releaseID and x.totnum = 1 +inner join releases on releases.ID = releasefiles.releaseID +where releasefiles.name like '%.exe' +and releases.categoryID not in (4000,4010,4020,4030,4040,4050) +group by releasefiles.releaseID "; +*/ + +// +// [3] delete all releases which contain a file with password.url in its +// +//$sql = "select distinct releasefiles.releaseID from releasefiles where name = 'password.url'"; + +// +// [4] delete all releases for a poster +// +//$sql = "select ID from releases where fromname = 'PowerBUS@gmail.com (PowerBUS)'"; + +// +// [5] delete all under a certain amount of completion +// +//$sql = "select ID from releases where completion != 0 and completion != 100 and completion < 99"; + +// +// [6] all audio which contains a file with .exe or install.bin in +// +//$sql = "select distinct r.ID from releasefiles rf inner join releases r on r.id = rf.releaseID and r.categoryID like '3%' where rf.name like '%.exe' or rf.name = 'install.bin'"; + +// +// [7] delete all releases for a name +// +//$sql = "select ID from releases where searchname like '%Friday The 13th The Series S03 -enjoy-%'"; + +// +// [8] delete all releases for a regex +// +//$sql = "select ID from releases where regexID = 1307"; + +// +// [9] delete all releases under a certain size (100MB) for a category +// +//$sql = "select ID from releases where categoryID like '2%' and size < 104857600"; + +$rel = $db->query($sql); +echo "about to delete ".count($rel)." release(s)"; + +foreach ($rel as $r) +{ + $releases->delete($r['ID']); +} diff --git a/lib/copy_this/misc/testing/dumpnfo.php b/lib/copy_this/misc/testing/dumpnfo.php new file mode 100644 index 000000000..878874477 --- /dev/null +++ b/lib/copy_this/misc/testing/dumpnfo.php @@ -0,0 +1 @@ +<?php // // Script will dump out all nfos in the system into a folder based on the date posted to usenet ./YYYYMMDD/release.nfo // Its not very efficient to pull them all out, should really work out which day you need and go from there. // define('FS_ROOT', realpath(dirname(__FILE__))); $db = new \newznab\db\DB(); $res = $db->queryDirect("select releases.searchname, releases.postdate, uncompress(releasenfo.nfo) as nfo from releases inner join releasenfo on releases.ID = releasenfo.releaseID and releasenfo.nfo is not null order by postdate"); while ($row = $db->getAssocArray($res)) { $dir = date("Ymd", strtotime($row["postdate"])); if (!file_exists($dir)) mkdir($dir); $filename = $dir."/".safeFilename($row["searchname"]).".nfo"; if (!file_exists($filename)) { $fh = fopen($filename, 'w'); fwrite($fh, \newznab\utility\Utility::cp437toUTF($row["nfo"])); fclose($fh); } } \ No newline at end of file diff --git a/lib/copy_this/misc/testing/fixTVRage.php b/lib/copy_this/misc/testing/fixTVRage.php new file mode 100644 index 000000000..51d102e27 --- /dev/null +++ b/lib/copy_this/misc/testing/fixTVRage.php @@ -0,0 +1,33 @@ +<?php + +define('FS_ROOT', realpath(dirname(__FILE__))); + + +$db = new \newznab\db\DB(); +$sql = "select distinct rageid from tvrage where rageid in (select rageid from tvrage where rageid != -2 group by rageid having count(*) > 1)"; +$rows = $db->query($sql); + +foreach ($rows as $row) +{ + $sql = "select id, rageid, tvdbid from tvrage where rageid = " . $row["rageid"]."\n"; + $tvrows = $db->query($sql); + $count = 0; + $keeprow="0"; + $firstrow = "0"; + + foreach ($tvrows as $tvrow) { + $count++; + if ($tvrow["tvdbid"] != 0) { + $keeprow = $tvrow["id"]; + } + if ($count == 1) { + $firstrow = $tvrow["id"]; + } + } + if ($keeprow != "0") + $firstrow = "0"; + + $sql = "delete from tvrage where rageid = ".$row["rageid"]." and (id != ".$keeprow." and id != ".$firstrow.")"; + $db->exec($sql); + echo "Cleaned - ".$row["rageid"]."\n"; +} diff --git a/lib/copy_this/misc/testing/fix_filesize.php b/lib/copy_this/misc/testing/fix_filesize.php new file mode 100644 index 000000000..f6ad4b6f0 --- /dev/null +++ b/lib/copy_this/misc/testing/fix_filesize.php @@ -0,0 +1,44 @@ +<?php + +/* +Filesize Fix Script +If after import you have a bunch of zero sized releases run this +Author: lordgnu <lordgnu@me.com> +*/ + +define('FS_ROOT', realpath(dirname(__FILE__))); + +use newznab\db\DB; + +$db = new DB; +$s = New Sites; +$nzb = new Nzb; + +$items = $db->query("SELECT ID,guid FROM releases WHERE size = 0"); +$total = count($items); +$compl = 0; +echo "Updating file size for " . count($items) . " release(s)\n"; +$site = $s->get(); + +while ($item = array_pop($items)) +{ + $nzbpath = $nzb->getNZBPath($item['guid'], $site->nzbpath); + + ob_start(); + @readgzfile($nzbpath); + $nzbfile = ob_get_contents(); + ob_end_clean(); + + $ret = $nzb->nzbFileList($nzbfile); + + $filesize = '0'; + + foreach ($ret as $file) { + $filesize = bcadd($filesize, $file['size']); + } + + $db->exec("UPDATE releases SET size = '{$filesize}' WHERE `ID` = '{$item['ID']}' LIMIT 1"); + + $compl++; + echo sprintf("[%6d / %6d] %0.2f",$compl, $total, ($compl/$total) * 100) . '%' . "\n"; +} diff --git a/lib/copy_this/misc/testing/fixreleasename.php b/lib/copy_this/misc/testing/fixreleasename.php new file mode 100644 index 000000000..6af290f5d --- /dev/null +++ b/lib/copy_this/misc/testing/fixreleasename.php @@ -0,0 +1,20 @@ +<?php +define('FS_ROOT', realpath(dirname(__FILE__))); + + +$db = new \newznab\db\DB(); + +//query to find rough matches +$rows = $db->query("SELECT ID, searchname from releases where searchname like '%QWERTY%'"); + +//loop around them applying some ham fisted regex +foreach ($rows as $row) +{ + $reg = '/^(\[QWERTY\] ")(?P<name>.*?(xvid|x264)\-.*?)"/i'; + preg_match($reg, $row["searchname"], $matches); + if (isset($matches["name"])) { + $db->exec(sprintf("update releases set searchname = %s, name = %s where ID = %d", + $db->escapeString($matches["name"]), $db->escapeString($matches["name"]), $row["ID"])); + echo $matches["name"]."\n"; + } +} diff --git a/lib/copy_this/misc/testing/getConsole.php b/lib/copy_this/misc/testing/getConsole.php new file mode 100644 index 000000000..a3ec51e52 --- /dev/null +++ b/lib/copy_this/misc/testing/getConsole.php @@ -0,0 +1,29 @@ +<?php +//This script will update all records in the cosole table + +define('FS_ROOT', realpath(dirname(__FILE__))); + +use newznab\db\DB; + +$console = new Console(true); + +$db = new DB(); + +$res = $db->queryDirect(sprintf("SELECT searchname, ID from releases where consoleinfoID IS NULL and categoryID in ( select ID from category where parentID = %d ) ORDER BY id DESC LIMIT %d", Category::CAT_PARENT_GAME, Console::NUMTOPROCESSPERTIME)); + +if ($res != null) { + while ($arr = $db->getAssocArray($res)) { + $gameInfo = $console->parseTitle($arr['searchname']); + if ($gameInfo !== false) { + echo 'Searching ' . $gameInfo['release'] . '<br />'; + $game = $console->updateConsoleInfo($gameInfo); + if ($game !== false) { + echo "<pre>"; + print_r($game); + echo "</pre>"; + } else { + echo '<br />Game not found<br /><br />'; + } + } + } +} \ No newline at end of file diff --git a/lib/copy_this/misc/testing/getCovers.php b/lib/copy_this/misc/testing/getCovers.php new file mode 100644 index 000000000..d68029771 --- /dev/null +++ b/lib/copy_this/misc/testing/getCovers.php @@ -0,0 +1,17 @@ +<?php +//This script will update all records in the movieinfo table + +define('FS_ROOT', realpath(dirname(__FILE__))); + +use newznab\db\DB; + +$movie = new Movie(true); + +$db = new DB(); + +$movies = $db->query("SELECT imdbID from movieinfo where cover = 0"); + +foreach ($movies as $mov) { + $mov = $movie->updateMovieInfo($mov['imdbID']); + sleep(1); +} \ No newline at end of file diff --git a/lib/copy_this/misc/testing/getPart.php b/lib/copy_this/misc/testing/getPart.php new file mode 100644 index 000000000..41b74e4cf --- /dev/null +++ b/lib/copy_this/misc/testing/getPart.php @@ -0,0 +1,19 @@ +<?php +define('FS_ROOT', realpath(dirname(__FILE__))); + +$grp = "a.b.grp"; +$msgid = "2df9e8a3$1$2314$6d4158fb@reader.xsnews.nl"; + +$nntp = new NNTP; +$nntp->doConnect(); +$sampleBinary = $nntp->getMessage($grp, $msgid); +$nntp->doQuit(); + +if ($sampleBinary === false) +{ + echo "-Couldnt fetch binary \n"; +} +else +{ + file_put_contents("test.part", $sampleBinary); +} \ No newline at end of file diff --git a/lib/copy_this/misc/testing/getTMdb.php b/lib/copy_this/misc/testing/getTMdb.php new file mode 100644 index 000000000..7d14b6433 --- /dev/null +++ b/lib/copy_this/misc/testing/getTMdb.php @@ -0,0 +1,21 @@ +<?php +// search tmdb or web for movie from a given name + +define('FS_ROOT', realpath(dirname(__FILE__))); + +$moviename = "Africa Screams"; +$movie = new Movie(); + +// #1 tmdb +// +//print_r($movie->searchTmdb($moviename)); + +// #2 search engine (google/bing) +//$buffer = getUrl("https://www.google.com/search?source=ig&hl=en&rlz=&btnG=Google+Search&aq=f&oq=&q=".urlencode($moviename.' site:imdb.com')); +$buffer = \newznab\utility\Utility::getUrl(['url' => 'http://www.bing.com/search?&q='.urlencode($moviename.' site:imdb.com')]); +if ($buffer !== false && strlen($buffer)) +{ + $imdb = $movie->parseImdbFromNfo($buffer); + echo sprintf("imdbid : %s\n", $imdb); + print_r($movie->fetchImdbProperties($imdb)); +} \ No newline at end of file diff --git a/lib/copy_this/misc/testing/getTVInfo.php b/lib/copy_this/misc/testing/getTVInfo.php new file mode 100644 index 000000000..958b6bed0 --- /dev/null +++ b/lib/copy_this/misc/testing/getTVInfo.php @@ -0,0 +1,19 @@ +<?php +define('FS_ROOT', realpath(dirname(__FILE__))); + +use newznab\db\DB; + +$t = new TvRage; + +$db = new DB(); + +$shows = $db->query("select name from releases where categoryID IN (select ID from category where parentID = 5000) limit 0, 50"); + +foreach ($shows as $show) { + $res = $t->parseNameEpSeason($show['name']); + $res['release'] = $show['name']; + + echo "<pre>"; + print_r($res); + echo "</pre>"; +} \ No newline at end of file diff --git a/lib/copy_this/misc/testing/memcache.php b/lib/copy_this/misc/testing/memcache.php new file mode 100644 index 000000000..9189460ec --- /dev/null +++ b/lib/copy_this/misc/testing/memcache.php @@ -0,0 +1,17 @@ +<?php + +// +// apt-get install php5-memcache +// + +$memcache_enabled = extension_loaded("memcached"); + +if ($memcache_enabled) + echo "extension loaded"; +else + echo "extension not loaded"; + +$mc = new Memcached(); +$mc->connect("localhost", 11211) ; + +print_r($mc->getStats()); diff --git a/lib/copy_this/misc/testing/movecat.php b/lib/copy_this/misc/testing/movecat.php new file mode 100644 index 000000000..16b2d0fdf --- /dev/null +++ b/lib/copy_this/misc/testing/movecat.php @@ -0,0 +1,27 @@ +<?php + +//This script moves releases from one category to another + +define('FS_ROOT', realpath(dirname(__FILE__))); + +use newznab\db\DB; + +$releases = new Releases(); +$db = new DB(); + +// +// [1] move mp3 files from other misc into audio mp3 +// +/* +$sql = "update releases inner join ( +select distinct rf.releaseID +from releasefiles rf +inner join releases r on r.ID = rf.releaseID +where rf.name like '%.mp3' +and r.categoryID like '7%') x on x.releaseID = releases.ID +set releases.categoryID = 3010;"; +*/ + + + +$db->exec($sql); \ No newline at end of file diff --git a/lib/copy_this/misc/testing/parread.php b/lib/copy_this/misc/testing/parread.php new file mode 100644 index 000000000..8d3e2c230 --- /dev/null +++ b/lib/copy_this/misc/testing/parread.php @@ -0,0 +1,45 @@ +<?php + +define('FS_ROOT', realpath(dirname(__FILE__))); + +use newznab\db\DB; + +$s = new Sites(); +$site = $s->get(); +$releases = new Releases(); +$db = new DB(); +$nzb = new Nzb(); +$nntp = new Nntp; + +// read pars for a release GUID, echo out any that look like a rar +$relguid = "249f9ec1f0d68d33b5fa85594ba1a47d"; + +$nzbfile = $nzb->getNZBPath($relguid, $site->nzbpath, true); +$nzbInfo = new nzbInfo; +$nzbInfo->loadFromFile($nzbfile); + +$nntp->doConnect(); + +echo $nzbInfo->summarize(); +foreach($nzbInfo->parfiles as $parfile) +{ + echo "Fetching ".$parfile['subject']."\n"; + $parBinary = $nntp->getMessages($parfile['groups'][0], $parfile['segments']); + if ($parBinary) + { + $par2 = new Par2info(); + $par2->setData($parBinary); + if (!$par2->error) + { + $parFiles = $par2->getFileList(); + foreach($parFiles as $file) + { + if (preg_match('/.*part0*1\.rar$/iS', $file['name']) || preg_match('/(?!part0*1)\.rar$/iS', $file['name']) || preg_match('/\.001$/iS', $file['name'])) + { + print_r($file); + } + } + } + } + unset($parBinary); +} \ No newline at end of file diff --git a/lib/copy_this/misc/testing/parsebooknames.php b/lib/copy_this/misc/testing/parsebooknames.php new file mode 100644 index 000000000..5851d163b --- /dev/null +++ b/lib/copy_this/misc/testing/parsebooknames.php @@ -0,0 +1 @@ +<?php define('FS_ROOT', realpath(dirname(__FILE__))); $titles = array(); $titles[] = 'Dack, Charles - Weather and Folk Lore of Peterborough and District (epub)'; $b = new Book(); foreach ($titles as $t) { $bookId = -2; $book = $b->parseAuthor($t); if ($book !== false) { echo 'Looking up: '.$book["author"].' - '.$book["title"].' ['.$t.']'."\n"; //check for existing book entry $bookCheck = $b->getBookInfoByName($book["author"], $book["title"]); if ($bookCheck === false) { // // get from amazon // $ret = $b->updateBookInfo($book["author"], $book["title"]); if ($ret !== false) { $bookId = $ret; } } else { $bookId = $bookCheck["ID"]; } } echo $bookId; } \ No newline at end of file diff --git a/lib/copy_this/misc/testing/predbUpdateAll.php b/lib/copy_this/misc/testing/predbUpdateAll.php new file mode 100644 index 000000000..f8ca81984 --- /dev/null +++ b/lib/copy_this/misc/testing/predbUpdateAll.php @@ -0,0 +1,6 @@ +<?php +define('FS_ROOT', realpath(dirname(__FILE__))); + +$p = new PreDB(true); +$p->nzpreUpdate(); +$p->processReleases(2000); \ No newline at end of file diff --git a/lib/copy_this/misc/testing/queryamazon.php b/lib/copy_this/misc/testing/queryamazon.php new file mode 100644 index 000000000..d3642b07b --- /dev/null +++ b/lib/copy_this/misc/testing/queryamazon.php @@ -0,0 +1 @@ +<?php define('FS_ROOT', realpath(dirname(__FILE__))); require_once (NN_LIBS . 'AmazonProductAPI.php'); $b = new Book(); $s = new Sites(); $site = $s->get(); $title = "Long Arm, The - Franz Habl "; $obj = new AmazonProductAPI($site->amazonpubkey, $site->amazonprivkey, $site->amazonassociatetag); try { $amaz = $obj->searchProducts($title, AmazonProductAPI::BOOKS, "TITLE"); $item = array(); $item["asin"] = (string) $amaz->Items->Item->ASIN; $item["url"] = (string) $amaz->Items->Item->DetailPageURL; $item["cover"] = (string) $amaz->Items->Item->LargeImage->URL; $item["author"] = (string) $amaz->Items->Item->ItemAttributes->Author; $item["dewey"] = (string) $amaz->Items->Item->ItemAttributes->DeweyDecimalNumber; $item["ean"] = (string) $amaz->Items->Item->ItemAttributes->EAN; $item["isbn"] = (string) $amaz->Items->Item->ItemAttributes->ISBN; $item["publisher"] = (string) $amaz->Items->Item->ItemAttributes->Publisher; $item["publishdate"] = (string) $amaz->Items->Item->ItemAttributes->PublicationDate; $item["pages"] = (string) $amaz->Items->Item->ItemAttributes->NumberOfPages; $item["title"] = (string) $amaz->Items->Item->ItemAttributes->Title; $item["review"] = ""; if (isset($amaz->Items->Item->EditorialReviews)) $item["review"] = trim(strip_tags((string) $amaz->Items->Item->EditorialReviews->EditorialReview->Content)); print_r($item); } catch(Exception $e) { echo "failed"; } \ No newline at end of file diff --git a/lib/copy_this/misc/testing/refreshMovie.php b/lib/copy_this/misc/testing/refreshMovie.php new file mode 100644 index 000000000..1916f7c6d --- /dev/null +++ b/lib/copy_this/misc/testing/refreshMovie.php @@ -0,0 +1,43 @@ +<?php + +define('FS_ROOT', realpath(dirname(__FILE__))); + +use newznab\db\DB; + +$movie = new Movie(true); +$db = new DB(); +$movies = array(); +$counter = 1; +$sleepsecsbetweenscrape = 1; + +//echo out the properties scraped from imdb for an ID +//print_r($movie->fetchImdbProperties("1375666")); + +// CASE 1 - UPDATE ALL RECORDS +//$movies = $db->query("SELECT imdbID from movieinfo"); + +// CASE 2 - UPDATE ALL WITH A BLANK TITLE +//$movies = $db->query("SELECT imdbID from movieinfo where title = ''"); + +// CASE 3 - UPDATE ALL RECORDS NOT UPDATED IN THE LAST 6 MONTHS +//$movies = $db->query("SELECT imdbID from movieinfo where updateddate < DATE_ADD(NOW(), INTERVAL -6 MONTH)"); + +// CASE 4 - UPDATE ALL RECORDS WHERE COVER IS EMPTY +//$movies = $db->query("SELECT imdbID from movieinfo where cover = 0"); + +// CASE 5 - UPDATE ALL WITH NO TRAILER +//$movies = $db->query("SELECT imdbID from movieinfo where trailer is null and tmdbid is not null"); + + +if (count($movies) == 0) +{ + echo "No records selected to update - either uncomment case or no matches found.\n"; + die(); +} + +echo "Updating ".count($movies)." records - Sleep interval ".$sleepsecsbetweenscrape." second(s)\n"; +foreach ($movies as $mov) { + echo "Updating ".$mov['imdbID']." (".$counter++."/".count($movies).")\n"; + $mov = $movie->updateMovieInfo($mov['imdbID']); + sleep($sleepsecsbetweenscrape); +} \ No newline at end of file diff --git a/lib/copy_this/misc/testing/regexverify.php b/lib/copy_this/misc/testing/regexverify.php new file mode 100644 index 000000000..7819cf913 --- /dev/null +++ b/lib/copy_this/misc/testing/regexverify.php @@ -0,0 +1,54 @@ +<?php +// +// This script is used to test the regular expressions identified +// within a newznab database are valid. +// +// by l2g +// +define('FS_ROOT', realpath(dirname(__FILE__))); + + +function handleError($errno, $errstr, $errfile, $errline, array $errcontext) +{ + // error was suppressed with the @-operator + if (0 === error_reporting()) { + return false; + } + + throw new ErrorException($errstr, 0, $errno, $errfile, $errline); +} +set_error_handler('handleError'); + +$regs = array( + "empty" => "", + "illformed" => "[](9()))))))))) [34543/34]", + "simple" => '"data.mp3', + ); + +$releases = new Releases(); +$db = new DB(); +# fetch enabled regular expression +$catsql = "select ID,groupname,regex from releaseregex where status = 1"; +$res = $db->query($catsql); +$total=count($res); +$errcnt=0; + +echo "\n"; +foreach ($res as $regexrow) +{ + foreach ($regs as $regex){ + try { + $res=preg_match($regexrow["regex"], $regex); + }catch(Exception $e){ + $errcnt++; + $strerr=str_pad((int) $errcnt,2," ",STR_PAD_LEFT); + echo "$strerr. id=".$regexrow["ID"]. + ", group=".$regexrow["groupname"]."\n"; + echo " regex='".$regexrow["regex"]."'\n"; + echo " error=".$e->getMessage()."\n\n"; + break; + } + } +} +echo "Scanned $total record(s), $errcnt error(s) found.\n"; +exit(($errcnt>0)?1:0); \ No newline at end of file diff --git a/lib/copy_this/misc/testing/removespecial.php b/lib/copy_this/misc/testing/removespecial.php new file mode 100644 index 000000000..0632b93a2 --- /dev/null +++ b/lib/copy_this/misc/testing/removespecial.php @@ -0,0 +1,10 @@ +<?php + +define('FS_ROOT', realpath(dirname(__FILE__))); + +$echoonly = false; +$limitedtotoday = true; +$verbose = true; + +$p = new Parsing($echoonly, $limitedtotoday, $verbose); +$p->removeSpecial(); diff --git a/lib/copy_this/misc/testing/rottentom.php b/lib/copy_this/misc/testing/rottentom.php new file mode 100644 index 000000000..66126a2bb --- /dev/null +++ b/lib/copy_this/misc/testing/rottentom.php @@ -0,0 +1,20 @@ +<?php +define('FS_ROOT', realpath(dirname(__FILE__))); + +$s = new Sites(); +$site = $s->get(); + +if (isset($site->rottentomatokey)) +{ + $rt = new RottenTomato($site->rottentomatokey); + + //print_r(json_decode($rt->getBoxOffice())); + //print_r(json_decode($rt->getInTheaters())); + //print_r(json_decode($rt->getOpening())); + //print_r(json_decode($rt->getUpcoming())); + //print_r(json_decode($rt->getDVDReleases())); + //print_r(json_decode($rt->getMovie("770805418"))); + //print_r(json_decode($rt->getReviews("770805418"))); + //print_r(json_decode($rt->getCast("770805418"))); + print_r(json_decode($rt->searchMovie("moviename"))); +} \ No newline at end of file diff --git a/lib/copy_this/misc/testing/spotnab.php b/lib/copy_this/misc/testing/spotnab.php new file mode 100644 index 000000000..0205fdc4a --- /dev/null +++ b/lib/copy_this/misc/testing/spotnab.php @@ -0,0 +1,530 @@ +<?php +// Author l2g +// Date: Mar 17th, 2013 +// Version: 0.97.4 +// +// Description: +// This script is an implementation of spotnet and newznab to which +// multiple servers can share comments and information amongst each other +// +// The implementation is based loosely on how spotweb works. If you don't know +// what spotweb is, feel free to Google it. +// +// With an spotnab, you have 2 options: +// 1. Fetch comments (and potential other things as we dream them up) from +// other newznab sources and apply them to your own comment section. +// +// Fetched content is scanned and decrypted using a password that the +// newznab server who posted it chooses to share with you. If you can't +// decrypt the post then you move along. Since all newznab servers choose +// to share and or not to share. Spotnab will only populate your database +// with comments from the sources who choose to share their comments +// with you. +// +// A few public keys will be configured out of the box so that you can +// retrieve your comments from existing active sites should you choose +// to enable them. +// +// 2. Post comments; send all the comments made by your local users of your +// site to usenet encrypted by your own secure private key. Only those you +// share your public key will be allowed to decrypt it for their own +// server. +// +// Releases are uniquely bundled and shared across NewzNab servers through the +// use of the releases table. To uniquely identify a release across remote +// servers we need to extract the Message-ID from the first segment of the first +// file of the matched release (as it was posted to usenet). This ID is unique +// to usenet, so it'll be unique to us as well. We can achive this information +// from parsing the NZB file generated by the NewzNab server. +// +// This value can be certain to not conflict and uniquely identify a release +// across all NewzNab Servers. +// +// Content is posted and retrieved to Usnet in JSON encrypted using the key +// belonging to the NewzNab Server. +// +// Structure is as follows: +// { +// server: { +// code: <string>, +// title: <string>, +// }, +// postdate_utc: 'YYYY-MM-DD hh:mm:ss.ms', +// comments: [ +// { +// gid: <char[32]>, +// cid: <char[32]>, +// comment: <string>, +// is_visible: <bool>, +// username: <string>, +// postdate_utc: 'YYYY-MM-DD hh:mm:ss', +// } +// ] +// } +// +// server: Meta information on the server that posted the spot. +// +// server +// -/ code: This is taken from the users local database `site` table. It is +// the `code` the user configured their newznab server as. +// +// -/ title: This is also taken from the users local database `site` table. It +// is the the `title` the user configured their newznab server as. +// +// postdate_utc: This is the current time measured in the number of seconds since +// the Unix Epoch (January 1 1970 00:00:00 GMT). This represents +// the local UTC time of when this message was posted. It doesn't +// reflect the age of the content to follow. +// +// comments: This is an array of comment objects +// +// comments +// -/ gid: This is the Global Identifier for the release the comment +// is in relation to. +// +// -/ cid: This is a unique global identifier used to identify the comment +// itself. This allows the server to publish the comment again +// if there is an update to it's data (such as toggling it to a +// hidden type). This should be used to prevent a duplicate +// entry in the comments table when dealing with remote content. +// +// -/ comment: This is the actual comment itself associated with the release +// +// -/ is_visible: Whether or not the comment should be marked visible or not. +// +// -/ username: The username of the person who made the comment. +// +// -/ postdate_utc: The timestamp (in UTC) that the comment was created at. +// + +/* + +INSTRUCTIONS +============ + +Both posting and fetching will 'NOT' work unless you've generated +Global Release ID values for all of your current releases... this is +done by running the command: + + #> php spotnab.php -g + +POSTING + 1. To run all of the SQL statements identifed above + + 2. You 'must' have all Global Release ID's defined for each + release or the comments associated with it will not be + included in the post. + + 3. Generate yourself your own set of SSL keys: + #> php spotnab.php -k + + 4. At this point your ready to post... If you run the following SQL + statement, you'll mark all your existing comments: + + -- Ensure spotnab posting is enabled: + UPDATE `site` set `value` = '1' WHERE `setting` = 'spotnabpost'; + + -- Posting actually uses this date as a reference to when + -- it last posted. So set it to a date so far back in time + -- that all your existing comments become declared as unposted. + + UPDATE `site` set `updateddate` = '1980-01-01 00:00:00' + WHERE `setting` = 'spotnabpost' AND `value` = '1'; + +FETCHING + 1. You need to acquire and enable sources. A source is as simple + as someone providing you their public key they generated using + the --keygen (-k) switch. + + 2. Fetch releases: + #> php spotnab.php -f + + 3. Consider fetching your own posts back just to test things out...: + + SET @key := (SELECT value FROM site WHERE setting = 'spotnabsitepubkey'); + INSERT INTO `spotnabsources` (`ID` , `username`, `useremail` , + `usenetgroup`, `publickey` , `active` , + `description` , `lastupdate` ) + VALUES ( NULL , 'nntp', 'spot@nntp.com', 'alt.binaries.backup', @key, + '1', '1', 'My Key Fetch Test', NULL); + + Then you can run the fetch release command again to poll for + stuff you posted already (if you did). + + #> php spotnab.php -f + +SHARING + 1. Use the -k switch on the tool to retrieve your public key... + share it... let people use the comments posted on your site + get them to do the same to you. Eliminating crappy content + couldn't be more easy. + + Spotnab now has a built in feature to post a discovery message + for others to grab automatically. Just call: + #> php spotnab.php -b + + You can also fetch messages from those who have already + posted their own discovery message by calling: + #> php spotnab.php -d + + Just note that anything auto-discovered is disabled by default + so you need to go into your options and 'enable' it if you + recognize or want to test out the source. +*/ + +define("FS_ROOT", realpath(dirname(__FILE__))); + +// Subject Lines will always be a hash key that helps scanning identify whether +// or not the contents are valid or not. the hash key contains is built +// by applying the password key against the md5 some of the message content +// itself. Unmatched content is ignored. + +$shortopts = ""; +$shortopts .= "G"; +$shortopts .= "g"; +$shortopts .= "r"; +$shortopts .= "p"; +$shortopts .= "f"; +$shortopts .= "t"; +$shortopts .= "k"; +$shortopts .= "o"; +$shortopts .= "K"; +$shortopts .= "d"; +$shortopts .= "b"; +$shortopts .= "F::"; + +$longopts = array( + "post", + "fetch", + "fetch-backfill::", + "discover", + "broadcast", + "test", + "populate-gid", + "populate-fix-gid", + "soft-reset", + "keygen", + "force-keygen", + "clean-orphan-comments" +); + +$options = getopt($shortopts, $longopts); + +function display_help(){ + echo "\n"; + echo "SpotNab v0.97.4, Author: l2g\n"; + echo "Syntax: spotnab.php <action>\n"; + echo "\n"; + echo "Actions:\n"; + echo " -g, --populate-gid This could be considered phase one of " + ."this project.\n"; + echo " requiring that your releases database" + ." table is up to date\n"; + echo " with all GID (Global Identifiers) so" + ." it can correctly\n"; + echo " communicate with other servers that " + ."share the same content\n"; + echo " from the servers configured.\n"; + echo " -G, --populate-fix-gid Same as -g except broken nzb files are " + ."also broken releases.\n"; + echo " Specifying this switch will remove " + ."these dead releses.\n"; + echo " -f, --fetch Get latest spotnab comments from " + ."usenet using the information\n"; + echo "\n"; + echo " -F=DAYS\n"; + echo " --fetch-backfill=DAYS Get latest spotnab comments as far back" + ." as the days specified.\n"; + echo "\n"; + echo " -p, --post Post latest updates from local system " + ."to usenet.\n"; + echo "\n"; + echo " -k, --keygen Generate a new SSL Public/Private Key " + ."pair only if one isn't\n"; + echo " already generated.\n"; + echo " -K, --force-keygen Generate a new SSL Public/Private Key " + ."pair\n"; + echo "\n"; + echo " -d, --discover Attempt to discovery all sources available.\n"; + echo "\n"; + echo " -o, --clean-orphan-comments\n"; + echo " Eliminate all fetched comments that you do not have a" + ." release\n"; + echo " associated with.\n"; + echo "\n"; + echo " -b, --broadcast Broadast information for others so they can discover.\n"; + echo "\n"; + echo " -r, --soft-reset Safely resets sources as though they were\n"; + echo " just added. This is ideal to do if you\n"; + echo " change usenet servers.\n"; + echo " -t, --test Produces a whole lot of garbage, but " + ."is used for testing\n"; + echo " the internals of the class...\n"; + echo "\n"; +} + +if(!$options){ display_help(); exit(1);} +if(!count($options)){ display_help(); exit(1);} + +$delete_broken_releases = false; +if(array_key_exists("G", $options) || + array_key_exists("populate-fix-gid", $options)){ + echo "Updating GID in releases table + fix ..."; + $spotnab = new SpotNab(); + $spotnab->processGID(0,5000,true); + echo "Done\n"; +} + +if(array_key_exists("g", $options) || + array_key_exists("populate-gid", $options)){ + echo "Updating GID in releases table ..."; + $spotnab = new SpotNab(); + $spotnab->processGID(); + echo "Done\n"; +} + +if(array_key_exists("r", $options) || + array_key_exists("soft-reset", $options)){ + echo "Soft Reseting Spotnab... "; + $spotnab = new SpotNab(); + $spotnab->soft_reset(); + echo "Done\n"; +} + +$force_keygen_save = false; +if(array_key_exists("K", $options) || + array_key_exists("force-keygen", $options)){ + $spotnab = new SpotNab(); + $spotnab->keygen(true, true); +} +else if(array_key_exists("k", $options) || + array_key_exists("keygen", $options)){ + $spotnab = new SpotNab(); + $spotnab->keygen(true); +} + +if(array_key_exists("p", $options) || + array_key_exists("post", $options)){ + echo "Posting... "; + $spotnab = new SpotNab(); + $spotnab->post(); + echo "Done\n"; +} + +if(array_key_exists("d", $options) || + array_key_exists("discover", $options)){ + echo "Discovering... "; + $spotnab = new SpotNab(); + $spotnab->fetch_discovery(); + echo "Done\n"; +} + +if(array_key_exists("F", $options) || + array_key_exists("fetch-backfill", $options)){ + $days = array_key_exists("F", $options)?$options["F"]:$options["fetch-backfill"]; + try{ + $days = abs(intval($days)); + }catch(Exception $e){ + $days = -1; + } + + if($days <= 0){ + echo "Error: A SpotNab fetch backfill requires you specify the number of days to look back.\n"; + echo "Syntax: php spontnab.php -F=<days>\n"; + exit(1); + } + echo "Fetching $days day(s) back ... "; + $spotnab = new SpotNab(); + $spotnab->fetch(time()-($days*86400)); + echo "Done\n"; + + +}else if (array_key_exists("f", $options) || + array_key_exists("fetch", $options)){ + echo "Fetching... "; + $spotnab = new SpotNab(); + $spotnab->fetch(); + echo "Done\n"; +} + +if(array_key_exists("b", $options) || + array_key_exists("broadcast", $options)){ + echo "Broadcasting... "; + $spotnab = new SpotNab(); + $spotnab->post_discovery(); + echo "Done\n"; +} + +if(array_key_exists("t", $options) || + array_key_exists("test", $options)){ + $spotnab = new SpotNab(); + + if($spotnab->has_openssl()) + { + printf("%s INFO - Testing SSL Key Generator ...", + date("Y-m-d H:i:s")); + $keys = $spotnab->keygen(false); + if(is_array($keys) && + array_key_exists("pubkey", $keys) && + array_key_exists("prvkey", $keys)) + { + $prvkey = $spotnab->decompstr($keys['prvkey']); + $pubkey = $spotnab->decompstr($keys['pubkey']); + $refc = $spotnab->getRandomStr(80); + $refd = $spotnab->decrypt($spotnab->encrypt($refc, $prvkey), $pubkey); + echo ($refc == $refd)?"Successful!\n":"Failed!\n"; + }else{ + echo "Failed!\n"; + } + + printf("%s INFO - Testing SSL encryption/decryption ...", + date("Y-m-d H:i:s")); + $preMsg = $spotnab->getRandomStr(800); + $postMsg = $spotnab->decrypt($spotnab->encrypt($preMsg)); + if($postMsg === false){ + echo "Failed!\n"; + }else if(!strcmp($preMsg, $postMsg)){ + echo "Successful!\n"; + }else{ + echo "Failed!\n"; + } + + printf("%s INFO - Testing small message encode/decode ...", + date("Y-m-d H:i:s")); + $before = array( + 'server' => array( + 'code' => 'l2g', + 'title' => 'l2g newznab' + ), + 'postdate_utc' => $spotnab->local2utc(), + 'comments' => array( + array( + 'gid' => 'ABCDEFHIJKLMNOPQRSTUVWXYZ0123456', + 'cid' => 'ABCDEFHIJKLMNOPQRSTUVWXYZ0123456', + 'comment' => 'testing comment 1', + 'username' => 'l2g', + 'is_visible' => 1, + 'postdate_utc' => $spotnab->local2utc(time()-86400) + ), + array( + 'gid' => 'ABCDEFHIJKLMNOPQRSTUVWXYZ0123456', + 'cid' => 'ABCDEFHIJKLMNOPQRSTUVWXYZ0123456', + 'username' => 'l2g-hater', + 'is_visible' => 1, + 'comment' => 'testing comment 2', + 'postdate_utc' => $spotnab->local2utc(time()-86000) + ) + ) + ); + $article = $spotnab->encodePost($before, Null, true); + if($article !== false){ + $after = $spotnab->decodePost($article[1]); + if($before === $after){ + echo "Successful!\n"; + }else{ + echo "Failed!\n"; + } + }else{ + echo "Failed!\n"; + } + printf("%s INFO - Testing big message encode/decode ...", + date("Y-m-d H:i:s")); + $before = array( + 'server' => array( + 'code' => 'l2g', + 'title' => 'l2g newznab' + ), + 'postdate_utc' => $spotnab->local2utc(), + 'comments' => array() + ); + for($i=0;$i<3000;$i++){ + // Build large post + $before['comments'][] =array( + 'gid' => 'ABCDEFHIJKLMNOPQRSTUVWXYZ0123456', + 'cid' => 'ABCDEFHIJKLMNOPQRSTUVWXYZ0123456', + 'comment' => $refc = $spotnab->getRandomStr(rand(15,200)), + 'username' => 'bb', + 'is_visible' => 1, + 'postdate_utc' => $spotnab->local2utc(time()-86400) + ); + } + $article = $spotnab->encodePost($before, Null, true); + if($article !== false){ + $after = $spotnab->decodePost($article[1]); + if($before === $after){ + echo "Successful!\n"; + }else{ + echo "Failed!\n"; + } + }else{ + echo "Failed!\n"; + } + + printf("%s INFO - Testing fake usenet parse ...", + date("Y-m-d H:i:s")); + // Fake group hash table + $hash = array(array( + 'ID' => 0, + 'key' => $spotnab->decompstr($keys['pubkey']), + 'user' => 'nntp', + 'email' => 'spot@nntp.com', + // We want to find new content, so to make our header + // new, we need to take our ref time and back down + // one second so it can be processed.. + 'ref' => $article[2]['Epoch']-1 + )); + + // Fake headers (use debug information from encodePost) + $headers = array($article[2]); + + $matched = $spotnab->process_comment_headers($headers, $hash, false); + if($matched !== false){ + $inserted = $matched[0]; + $updated = $matched[1]; + echo ($matched > 0)?"Successful!\n":"Failed!\n"; + }else{ + echo "Failed\n"; + } + }else{ + printf("%s WARNING - openssl is not correctly installed; broadcasts and posts will be disabled.\n", + date("Y-m-d H:i:s")); + } + + printf("%s INFO - Testing UTC/Local conversions [1/6]...", + date("Y-m-d H:i:s")); + $refa = $spotnab->utc2local(); + $refb = $spotnab->utc2local($spotnab->local2utc($refa)); + echo ($refa == $refb)?"Successful!\n":"Failed!\n"; + printf("%s INFO - Testing UTC/Local conversions [2/6]...", + date("Y-m-d H:i:s")); + $refa = $spotnab->local2utc(); + $refb = $spotnab->local2utc($spotnab->utc2local($refa)); + echo ($refa == $refb)?"Successful!\n":"Failed!\n"; + printf("%s INFO - Testing UTC/Local conversions [3/6]...", + date("Y-m-d H:i:s")); + $refa = $spotnab->local2utc(date("Y-m-d H:i:s")); + $refb = $spotnab->local2utc($spotnab->utc2local($refa)); + echo ($refa == $refb)?"Successful!\n":"Failed!\n"; + printf("%s INFO - Testing UTC/Local conversions [4/6]...", + date("Y-m-d H:i:s")); + $refa = $spotnab->utc2local(time()); + $refb = $spotnab->utc2local($spotnab->local2utc($refa)); + echo ($refa == $refb)?"Successful!\n":"Failed!\n"; + printf("%s INFO - Testing UTC/Local conversions [5/6]...", + date("Y-m-d H:i:s")); + $refa = $spotnab->local2utc(time()); + $refb = $spotnab->local2utc($spotnab->utc2local($refa)); + echo ($refa == $refb)?"Successful!\n":"Failed!\n"; + printf("%s INFO - Testing UTC/Local conversions [6/6]...", + date("Y-m-d H:i:s")); + $refa = $spotnab->utc2local(gmdate("Y-m-d H:i:s")); + $refb = $spotnab->utc2local($spotnab->local2utc($refa)); + echo ($refa == $refb)?"Successful!\n":"Failed!\n"; +} + +if(array_key_exists("o", $options) || + array_key_exists("clean-orphan-comments", $options)){ + echo "Removing orphan comments..."; + $spotnab = new SpotNab(); + printf("%d record(s) removed.\n", $spotnab->orphan_comment_clean()); +} \ No newline at end of file diff --git a/lib/copy_this/misc/testing/test_blacklist.php b/lib/copy_this/misc/testing/test_blacklist.php new file mode 100644 index 000000000..c93049ce7 --- /dev/null +++ b/lib/copy_this/misc/testing/test_blacklist.php @@ -0,0 +1,494 @@ +<?php +// +// This script is allows you to perform post blacklist scanning +// Read about the flags below before using this script. +// +// The intent of this script is to try and eliminate garbage +// entries. +// +// by l2g +// +define('FS_ROOT', realpath(dirname(__FILE__))); + +use newznab\db\DB; + + +# If satisfied with what is matched, set this to true and have +# matched content removed. +# This is a DANGEROUS switch to change. Be sure your absolutely +# satisfied with the regular expressions being matched are bad. +# You'd ideally want to change this flag back to false when you +# resume testing. +$purgeMatched=false; + +# When this flag is set to true, the database blacklist is applied +# to your existing nn db. If you set this to false, then the +# blacklist array below is applied instead +$use_NNRegexDB=false; + +# By default it looks at all the headers in the database, but sometimes +# if your database is just too big and you want to expermeint with different +# regular expressions, you can set this flag to false, and instead start +# playing with the $res table below labled as Test DB data +$use_NNReleasesDB=true; + +# Categorized content can be futher subjected to size restrictions 'IF' +# your database is configured for such. +# This allows you to filter out crap that makes no sense being +# idenified as the category it is based on the category sizing +# Note: This is expermental at this point and requires an update to the DB to +# work correctly. +# +# ALTER TABLE `category` ADD `minsize` INT UNSIGNED NOT NULL DEFAULT '0' AFTER `status` , +# ADD `maxsize` INT UNSIGNED NOT NULL DEFAULT '0' AFTER `minsize` ; +# +# ;; Update tvshows.SD to set a min value of 30MB (in bytes) +# UPDATE `newznab`.`category` SET `minsize` = '31457280' WHERE `category`.`ID` =5030 LIMIT 1 ; +# ;; Update movies.SD to set a min value of 50MB (in bytes) +# UPDATE `newznab`.`category` SET `minsize` = '52428800' WHERE `category`.`ID` =2030 LIMIT 1 ; +# +# This also requires a few functions in the lib/category.php +# Better just wait before enabling this :) +$use_CategorySizeRestrictions=true; +# This flag is only used if $use_CategorySizeRestrictions (above) is set to true. +# setting this value to false, will have all category restrictions defined in the +# static table below take effect... otherwise, the script will query the database (it's assumed +# that all the proposed changes were accepted and pushed into the DB). Leave this value to +# false until it is certain the database changes have been pushed. When these chagnes are pushed +# this flag will be merged with the above. +$use_NNCategorySizeRestrictions=false; + +# Completion Restriction allows you to remove content that is older then +# X hrs and is less then 'Y%' complete. +# Why keep content in the database that can't be put back together +$use_CompletionRestrictions=true; +# The precentage *must be less then (or equal to) 100* to accept 'up to' +$completionAllowable=90; +# The number of hours the release has aged and still hasn't met the allowable +# completion percentage (in seconds) 10800 is equal to 3 hrs +$completionSec=10800; + +# check or the article is considered bogus. This greatly increasese +# the processing time against the database. +# Be warned that if your cataloging music, almost every band out there +# spells their name with something that does not coincide with a dictionary +# value. +$use_spellCheck=false; + +# Identify the number of dictionaries you want to check the spelling +# against. International spell checking might include 'ge', ' +$spellCheckLang=array('en'); + +# International (uncomment the below) +#$spellCheckLang=array('en', 'fr', 'it', 'ge', 'es', 'nl'); + +# Exceptions are bad spellings that exist in a filename but still +# mark it valid; This list is not case sensitive, so add any +# keywords that should not be considered while searching +$spellExceptions=array( + # Some good tokens + 'xvid', 'DVD', 'DVDRip', 'Bluray', 'x264', '480p', '720p', '1080p', + 'HDRIP', + # TV Episode Tags + 'S[0-9]{1,2}([. -]*E[0-9]{1,2}$|$)', + + # Tv Series release groups + "BARC0DE", "DIMENSION", "LOL", "WEB-DL", "SUBLiME", "2HD", "FMQ", + "BIA", + + # MP3/FLAC Groups + "FiH", "SDR", + + # Software Groups + "LAXiTY", +); + +# Some default category restrictions to play with for those who haven't +# updated their database yet and would still like size restrictions +# in place. +$categoryRestrictions=array( + # TV Standard Def (SD) set a 30MB Min restriction + Category::CAT_TV_SD=>array('min'=>31457280, 'max'=>PHP_INT_MAX), + # TV High Def (HD) set a 40MB Min restriction + Category::CAT_TV_HD=>array('min'=>41943040, 'max'=>PHP_INT_MAX), + # Movies Standard Def (SD) set a 50MB Min restriction + Category::CAT_MOVIE_SD=>array('min'=>52428800, 'max'=>PHP_INT_MAX), + # Movies High Def (HD) set a 80MB Min restriction + Category::CAT_MOVIE_HD=>array('min'=>83886080, 'max'=>PHP_INT_MAX), + # Movies Other set a 30MB Min restriction + Category::CAT_MOVIE_OTHER=>array('min'=>31457280, 'max'=>PHP_INT_MAX), + # Bluray movies, 350MB Min restriction + Category::CAT_MOVIE_BLURAY=>array('min'=>367001600, 'max'=>PHP_INT_MAX), +); + +# Throttle cleanup/searching by performing batches... the larger +# the number, the faster processing will go, but will demand more +# system memory... +$batch=500; + +# Throttle +# The throttle allows a scan of your database without impacting performance +# to the public who may or may not be using your database. it also reduces +# the cpu demand of the cleanup. Set this value to 0 if your system is +# private and dedicated to yourself for the best speed. It identifies +# the number of seconds to sleep for between each batch +$throttle=0.5; + +# This blacklist is an aray of regular expressions that you can use +# to test with (sometimes it's easier to update a table infront of +# you as a developer then going back and making a database change +# and then returning to run the script. +$blacklist = array( + # random string of crap + array("groupname"=>"alt.binaries.*", "regex"=>'^[a-z0-9]{1,80}([0-9-]+$|$)'), + # Missing blacklist catching of foreign content + array("groupname"=>"alt.binaries.*", "regex"=>'[-.](FR|DE|ITA)[-.]'), + # Common German Keywords + array("groupname"=>"alt.binaries.*", "regex"=>'(^|[.\/ \-]+)(ohne|das|der|und|fuer|ersten|leicht|meinem|zum|aus|dem|blitzlicht|alle|grosse|blitzen|ich|zed|sed)([.\/ \-]+|$)'), + # random string of crap in alt.binaries.sounds.mp3, and alt.binaries.multimedia + array("groupname"=>"alt.binaries.*", "regex"=>'^[a-z0-9]{5} [0-9]{8} [0-9]{3}$'), + # random crap like: acef826f-6c8b-405c-b7f2-c9c143d726a8 + array("groupname"=>"alt.binaries.*", "regex"=>'^[a-z0-9]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}$'), + array("groupname"=>"alt.binaries.*", "regex"=>'^[a-z0-9.]+\.BDR$'), + array("groupname"=>"alt.binaries.*", "regex"=>'^\([0-9.]+\)$'), + + # Password protected content that was marked by the poster + array("groupname"=>"alt.binaries.*", "regex"=>'\[password\]'), +); + +# Test DB Data; if you plan on using this, you need to set the $use_NNReleasesDB to false +$test_headers = array( + # Set id's to 0 so id's are purged unessisarily when testing + array('ID'=>0, 'groupname'=>"alt.binaries.multimedia", 'name'=>"1204odayrtgh6j7app"), + array('ID'=>0, 'groupname'=>"alt.binaries.multimedia", 'name'=>"BB555"), + array('ID'=>0, 'groupname'=>"alt.binaries.multimedia", 'name'=>"bnedhe8utrh5tnbg9"), + array('ID'=>0, 'groupname'=>"alt.binaries.multimedia", 'name'=>"Uoaaqunio-396653289-201212201118"), + array('ID'=>0, 'groupname'=>"alt.binaries.multimedia", 'name'=>"acef826f-6c8b-405c-b7f2-c9c143d726a8"), + array('ID'=>0, 'groupname'=>"alt.binaries.multimedia", 'name'=>"ich26389"), + array('ID'=>0, 'groupname'=>"alt.binaries.multimedia", 'name'=>"GkTNPvg3"), + array('ID'=>0, 'groupname'=>"alt.binaries.multimedia", 'name'=>"RVL 25 12 2012 G O M S BDR"), + array('ID'=>0, 'groupname'=>"alt.binaries.multimedia", 'name'=>"25 12 2012 M S R BDR"), + array('ID'=>0, 'groupname'=>"alt.binaries.multimedia", 'name'=>"23YKC 20121212 013"), +); + +function handleError($errno, $errstr, $errfile, $errline, array $errcontext) +{ + // this function makes it easier to catch regular expression errors + // found + if (0 === error_reporting()) { + return false; + } + throw new ErrorException($errstr, 0, $errno, $errfile, $errline); +} +set_error_handler('handleError'); + +function get_block($offset, $batch) +{ + global $use_NNReleasesDB; + static $retrieved=false; + if(!$use_NNReleasesDB){ + // use a retrieved boolean for test data so content + // is only fetched once. + if(!$retrieved && $offset > 0){ + return Null; + } + global $test_headers; + // toggle retrieved content on test data + $retrieved=true; + return $test_headers; + } + + $catsql = "SELECT releases.*,groups.name as groupname FROM " + ."releases LEFT JOIN groups on releases.groupID = groups.ID "; + $db = new DB(); + return $db->query($catsql.sprintf(' LIMIT %d,%d', $offset, $batch)); +} + +$db = new DB(); + +$errcnt=0; +$total=0; +$offset=0; + +# Dictionary +$pspelldict=array(); + +# Completion Refernece Time in past +$completionRef = strtotime("-$completionSec seconds"); + +# Scan header for spelling...; at least 1 word has to match the spelling +if($use_spellCheck && !function_exists('pspell_check')){ + echo "Note: Disabling spell checking as it is not available in your PHP installation.\n"; + echo " Consider the following to enable it:"; + echo " ubuntu #> sudo apt-get install php5-pspell\n"; + echo " redhat #> yum install php-pspell\n"; + echo " other #> # re-compile php with --with-pspell flag\n"; + $use_spellCheck=false; +} + +$binaries = new Binaries(); +if($use_NNRegexDB) + # Over-ride Blacklist up top and use database + $blacklist = $binaries->getBlacklist(true); + +while($res=get_block($offset, $batch)){ + + $subtotal=count($res); + $total+=$subtotal; + + $release = new Releases(); + $category = new Category(); + + // Track error count changes + $_errcnt=$errcnt; + foreach ($res as $header) + { + // if a white list is detected we now are required to + // only accept the entry if it matches at least 1 whitelist + // while a blacklist will over-ride all + $whitelist = array(); + $matches_whitelist = false; + + foreach ($blacklist as $bl) + { + // opttype = 1 -> Blacklist (Default) + // opttype = 2 -> Whitelist + $opttype = Binaries::OPTYPE_BLACKLIST; + if (array_key_exists ('opttype' , $bl)){ + $opttype = intval($bl['opttype']); + } + + // Regular expression + $regex = $bl['regex']; + + // Default msgcol is subject + $msgcol = Binaries::BLACKLIST_FIELD_SUBJECT; + $parse = $header['name']; + if (array_key_exists ('msgcol' , $bl)){ + $msgcol = intval($bl['msgcol']); + } + + switch($msgcol) + { + case Binaries::BLACKLIST_FIELD_FROM: + if(!array_key_exists ('fromname' , $bl)){ + # we only process fromname if we found it... otherwise we keep going + continue; + } + $parse = $header['fromname']; + break; + case Binaries::BLACKLIST_FIELD_MESSAGEID: + # unsupported; you can't get this information from an already + # populated database + continue; + }; + + if ($opttype == Binaries::OPTYPE_WHITELIST){ + // at least 1 whitelist found... + // this means we have to match it or be rejected + $whitelist[] = $regex; + } + + try + { + $group_check = preg_match('/^'.$bl['groupname'].'$/i', $header['groupname']); + } + catch(Exception $e) + { + # Support letting the user know when there is a bad + # regular expression entry abort futher checks + $strerr=str_pad((int) $errcnt,2," ",STR_PAD_LEFT); + echo "$strerr. id=".$bl["ID"]. + ", group=".$header["groupname"]."\n"; + echo " regex='".$bl["groupname"]."'\n"; + echo " error=".$e->getMessage()."\n\n"; + exit(1); + } + + if ($group_check) + { + try + { + $blacklist_check = preg_match('/'.$regex.'/i', $parse); + // White lists react in the invert manner... something that + // doesn't match causes us to keep going + if($opttype == Binaries::OPTYPE_WHITELIST && $blacklist_check){ + // invert check since it's a good thing we matched + $blacklist_check=false; + // Flag that we matched the white list + $matches_whitelist = true; + } + } + catch(Exception $e) + { + # Support letting the user know when there is a bad + # regular expression entry abort futher checks + $strerr=str_pad((int) $errcnt,2," ",STR_PAD_LEFT); + if(isset($bl["ID"])) + echo "$strerr. id=".$bl["ID"].", "; + echo " name=".$header["name"]."\n"; + echo " regex=$regex\n"; + echo " error=".$e->getMessage()."\n\n"; + exit(1); + } + + if ($blacklist_check) + { + $errcnt++; + echo 'BL: /'.$bl['regex'].'/i matched '.$header['ID'].'/'.$header['name']. + " (".$header['groupname'].")\n"; + if ($purgeMatched && isset($header['ID']) && $header['ID'] > 0){ + // Support purging if enabled + $release->delete($header['ID']); + } + # ensure whitelist flags are off to avoid extra processing + # at the end of this loop (Below) + $whitelist = array(); + break; + } + + if($use_CategorySizeRestrictions == true && $header['categoryID']) + { + $sizes = null; + if($use_NNCategorySizeRestrictions){ + $sizes = $category->getSizeRangeById($header['categoryID']); + }else if (array_key_exists ($header['categoryID'], $categoryRestrictions)){ + $sizes = $categoryRestrictions[$header['categoryID']]; + } + if(is_array($sizes)){ + # Restrictions are in place + $totalSize=intval($header['size']); + if(!($totalSize >= $sizes['min'] && $totalSize < $sizes['max'])) + { + $errcnt++; + echo 'BL: size restrictions '.$header['ID'].'/'.$header['name']. + " (".$header['groupname'].")\n"; + if ($purgeMatched && isset($header['ID']) && $header['ID'] > 0){ + // Support purging if enabled + $release->delete($header['ID']); + } + # ensure whitelist flags are off to avoid extra processing + # at the end of this loop (Below) + $whitelist = array(); + break; + } + } + } + + if($use_CompletionRestrictions == true){ + $lastUpdate=strtotime($header['updatedate']); + $completion=intval($header['completion']); + + if($completion < $completionAllowable && $lastUpdate < $completionRef) + { + $errcnt++; + echo 'BL: incomplete '.$header['ID'].'/'.$header['name']. + " (".$header['groupname'].")\n"; + if ($purgeMatched && isset($header['ID']) && $header['ID'] > 0){ + // Support purging if enabled + $release->delete($header['ID']); + } + # ensure whitelist flags are off to avoid extra processing + # at the end of this loop (Below) + $whitelist = array(); + break; + } + } + + if($use_spellCheck == true && + $opttype == Binaries::OPTYPE_BLACKLIST && + $msgcol == Binaries::BLACKLIST_FIELD_SUBJECT){ + + # Track matched + $matched=0; + # First extract the words + $keywords = preg_split('/[^a-z0-9]+/i', $parse); + foreach($spellCheckLang as $lang){ + if (!array_key_exists ($lang , $pspelldict)) + $pspelldict[$lang] = pspell_new($lang); + foreach($keywords as $kw){ + foreach($spellExceptions as $exception){ + if(preg_match('/'.$exception.'/i', $kw)){ + $matched++; + break; + } + } + if($matched>0)break; + + if(pspell_check($pspelldict[$lang], $kw)){ + $matched++; + break; + } + } + # we only need to match once to presume the data + # is good + if($matched>0)break; + } + # how did we do for spelling matches + if(!$matched){ + $errcnt++; + echo 'BL: due to bad spelling '.$header['ID'].'/'.$header['name']. + " (".$header['groupname'].")\n"; + if ($purgeMatched && isset($header['ID']) && $header['ID'] > 0){ + // Support purging if enabled + $release->delete($header['ID']); + } + # ensure whitelist flags are off to avoid extra processing + # at the end of this loop (Below) + $whitelist = array(); + break; + } + } + } + } + + # We parsed entire matching list entries at this point.. now we need + # to handle the whitelist (if it was enabled) + if(count($whitelist) > 0 && !$matches_whitelist) + { + $errcnt++; + $first_loop=true; + foreach ($whitelist as $entry){ + if($first_loop) + { + $first_loop=false; + } + else + { + echo '\n'; + } + echo 'WL: /'.$bl['regex'].'/i'; + } + echo ' failed to match '.$header['ID'].'/'.$header['name']. + " (".$header['groupname'].")\n"; + + if ($purgeMatched && $header['ID'] > 0){ + // Support purging if enabled + $release->delete($header['ID']); + } + } + } + if(!$purgeMatched || $_errcnt==$errcnt){ + # No changes... update batch + $offset+=$batch; + } + + if($subtotal == $batch){ + // Presume there is more content to come + // throttle request + if($throttle > 0.0){ + sleep($throttle); + } + } +} +echo "Scanned $total record(s), $errcnt match(es) found.\n"; +if($errcnt >0){ + if(!$purgeMatched){ + echo "Note: This scan was performed in a safe read-only mode.\n"; + echo " If you are satisfied with the output as being 'garbage/spam'\n". + " then consider editing this file and setting the \$purgeMatched flag to 'true'\n"; + }else{ + echo "Note: This scan was performed in a write mode; all content matched was removed.\n"; + } +} +exit(($errcnt>0)?1:0); diff --git a/lib/copy_this/misc/testing/test_regex.php b/lib/copy_this/misc/testing/test_regex.php new file mode 100644 index 000000000..c74502047 --- /dev/null +++ b/lib/copy_this/misc/testing/test_regex.php @@ -0,0 +1,54 @@ +<?php +// +// This script is used to test the regular expressions identified +// within a newznab database are valid. +// +// by l2g +// +define('FS_ROOT', realpath(dirname(__FILE__))); + +use newznab\db\DB; + +function handleError($errno, $errstr, $errfile, $errline, array $errcontext) +{ + // error was suppressed with the @-operator + if (0 === error_reporting()) { + return false; + } + + throw new ErrorException($errstr, 0, $errno, $errfile, $errline); +} +set_error_handler('handleError'); + +$regs = array( + "empty" => "", + "illformed" => "[](9()))))))))) [34543/34]", + "simple" => '"data.mp3', + ); + +$db = new DB(); +# fetch enabled regular expression +$catsql = "select ID,groupname,regex from releaseregex where status = 1"; +$res = $db->query($catsql); +$total=count($res); +$errcnt=0; + +echo "\n"; +foreach ($res as $regexrow) +{ + foreach ($regs as $regex){ + try { + $res=preg_match($regexrow["regex"], $regex); + }catch(Exception $e){ + $errcnt++; + $strerr=str_pad((int) $errcnt,2," ",STR_PAD_LEFT); + echo "$strerr. id=".$regexrow["ID"]. + ", group=".$regexrow["groupname"]."\n"; + echo " regex='".$regexrow["regex"]."'\n"; + echo " error=".$e->getMessage()."\n\n"; + break; + } + } +} +echo "Scanned $total record(s), $errcnt error(s) found.\n"; +exit(($errcnt>0)?1:0); \ No newline at end of file diff --git a/lib/copy_this/misc/testing/tidynzbfolder.php b/lib/copy_this/misc/testing/tidynzbfolder.php new file mode 100644 index 000000000..8c1f2a6c8 --- /dev/null +++ b/lib/copy_this/misc/testing/tidynzbfolder.php @@ -0,0 +1,46 @@ +<?php +define('FS_ROOT', realpath(dirname(__FILE__))); + +use newznab\db\DB; + +$s = new Sites(); +$site = $s->get(); +$db = new DB(); +$r = new Releases(); + +// +// Option One - delete all from the database where it exists on disk, but not in the db +// +/* +$it = new RecursiveDirectoryIterator($site->nzbpath); +foreach(new RecursiveIteratorIterator($it) as $file) +{ + $releaseGUID = str_replace(".nzb.gz", "", $file->getFilename()); + $rel = $db->queryOneRow(sprintf("SELECT ID from releases where guid = %s", $db->escapeString($releaseGUID))); + if (!$rel) + { + $r->delete($releaseGUID, true); + } + else + { + echo "not deleting ".$file->getFilename()."\n"; + } +} +*/ + + +// +// Option Two - delete all from the database where it doesnt exist on disk +// +/* + $res = $db->queryDirect("select guid from releases"); + while ($row = $db->getAssocArray($res)) + { + $nzbpath = $site->nzbpath.substr($row["guid"], 0, 1)."/".$row["guid"].".nzb.gz"; + if (!file_exists($nzbpath)) + { + echo "deleted ".$row["guid"]; + $r->delete($row["guid"], true); + } + } +*/ \ No newline at end of file diff --git a/lib/copy_this/misc/testing/timetest.php b/lib/copy_this/misc/testing/timetest.php new file mode 100644 index 000000000..716e7ef45 --- /dev/null +++ b/lib/copy_this/misc/testing/timetest.php @@ -0,0 +1,27 @@ +<?php +//This Script Verifies your System Time vs Myself Time vs PHP Time +define('FS_ROOT', realpath(dirname(__FILE__))); + +use newznab\db\DB; +$res=""; + +$db = new DB(); +$res = $db->queryonerow( sprintf("Select now()")); +foreach($res as $time){ +echo "Mysql Time Is Now ".$time."\n";} +$res=""; +$res = date('r'); +echo "PHP Time Is Now ".$res."\n"; +$res=""; + +if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') +{ + exec("time /t", $res); + echo "System Time is Now ".$res['0']."\n"; +} +else +{ + exec("date", $res); + echo "System Time is Now ".$res['0']."\n"; +} + diff --git a/lib/copy_this/misc/testing/transactiontest.php b/lib/copy_this/misc/testing/transactiontest.php new file mode 100644 index 000000000..7f9b0c706 --- /dev/null +++ b/lib/copy_this/misc/testing/transactiontest.php @@ -0,0 +1,44 @@ +<?php + + +try { + // Create the first database class instance (which will initialize the PDO connection) + $db = new DB(); + + // For debug set the error mode + $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + + // Start the transaction + if( $db->beginTransaction() ) + { + // Loop 20 times + for($i=1 ; $i<=20 ; $i++ ) + { + // Header + echo "--[ Insert run: {$i} ]----------------------------------------". PHP_EOL; + + // Create a new db class instance (multiple can exist) + $newDb = new DB(); + + // Check that there is a new db class instance, but no new PDO instance + var_dump( $newDb, $newDb->getPDO() ); + + // Insert some data + $sql = sprintf(" + INSERT INTO `testdata` + (`id` ,`field1` ,`field2` ,`field3` ,`field4`) + VALUES + ('%s', '%s', '%s', '%s', '%s')", $i, $i, $i, $i, $i + ); + $newDb->exec( $sql ); + + // Check for inserted data + var_dump( $newDb->query( sprintf( "SELECT * FROM `testdata` WHERE id = %d", $i ) ) ); + } + + // Now rollback using the last db class instance + var_dump( $newDb->rollback() ); + } +} catch(PDOException $e) { + var_dump( $e ); +} \ No newline at end of file diff --git a/lib/copy_this/misc/testing/updateCategories.php b/lib/copy_this/misc/testing/updateCategories.php new file mode 100644 index 000000000..569ea6e37 --- /dev/null +++ b/lib/copy_this/misc/testing/updateCategories.php @@ -0,0 +1,40 @@ +<?php +//This script will rerun all releases against Category.php +define('FS_ROOT', realpath(dirname(__FILE__))); + +use newznab\db\DB; + +$db = new DB(); +$category = new Category(); +$changedcount = 0; +$rescount = 0; + +// +// [1] change for all where the regex isnt aimed at a specific category (affects most releases) +// +//$res = $db->queryDirect("select r.id as id, r.searchname as searchname, g.name as groupname, r.categoryID as rcat from releases r, releaseregex rr, groups g where r.regexid=rr.id and g.ID = r.groupID and rr.categoryid is null"); + +// +// [2] update for all in a category +// +//$res = $db->queryDirect("select r.id as id, r.searchname as searchname, g.name as groupname, r.categoryID as rcat from releases r inner join groups g on g.ID = r.groupID where r.categoryID in (6010, 6020, 6030, 6040)"); + +// +// [3] reset all flac with hashed names +// +//$res = $db->queryDirect("select releases.ID as id, searchname as searchname, groups.name as groupname, releases.categoryID as rcat from releases join groups on groups.ID = releases.groupID where length(searchname) = 40 and groups.name like 'alt.binaries.sounds.flac'"); + +while ($rel = $db->getAssocArray($res)) +{ + $rescount++; + $categoryID = $category->determineCategory($rel['groupname'], $rel['searchname']); + if (($categoryID != $rel['rcat']) && ($categoryID != '7900')) + { + $changedcount ++; + echo "Changing category for ".$rel['searchname']." New (".$categoryID.") Old (".$rel['rcat'].")\n"; + $db->exec(sprintf("update releases SET categoryID = %d WHERE ID = %d", $categoryID, $rel['id'])); + } +} + +echo $rescount." releases \n"; +echo $changedcount." releases changed\n"; diff --git a/lib/copy_this/misc/testing/updateTVRage.php b/lib/copy_this/misc/testing/updateTVRage.php new file mode 100644 index 000000000..97b593e2a --- /dev/null +++ b/lib/copy_this/misc/testing/updateTVRage.php @@ -0,0 +1,21 @@ +<?php +define('FS_ROOT', realpath(dirname(__FILE__))); + +use newznab\db\DB; + +$db = new DB(); +$t = new TvRage(); + +// +// all rage entries with a blank description +$rows = $db->query("select ID, releasetitle from tvrage + where description is null + and rageID in (select distinct rageID from releases) + order by ID desc"); + +echo "Updating ".count($rows)." entries \n"; + +foreach ($rows as $row) { + $t->refreshRageInfo($row["ID"]); + echo "Refreshing ".$row["releasetitle"]."\n"; +} \ No newline at end of file diff --git a/lib/copy_this/misc/testing/update_cleanup.php b/lib/copy_this/misc/testing/update_cleanup.php new file mode 100644 index 000000000..98250ec52 --- /dev/null +++ b/lib/copy_this/misc/testing/update_cleanup.php @@ -0,0 +1,9 @@ +<?php +define('FS_ROOT', realpath(dirname(__FILE__))); + +$echoonly = true; +$limittotoday = false; +$verbose = true; + +$p = new Parsing($echoonly, $limittotoday, $verbose); +$p->cleanup(); \ No newline at end of file diff --git a/lib/copy_this/misc/testing/update_parsing.php b/lib/copy_this/misc/testing/update_parsing.php new file mode 100644 index 000000000..a6f3591a9 --- /dev/null +++ b/lib/copy_this/misc/testing/update_parsing.php @@ -0,0 +1,9 @@ +<?php +define('FS_ROOT', realpath(dirname(__FILE__))); + +$echoonly = false; +$limittotoday = false; +$verbose = true; + +$p = new Parsing($echoonly, $limittotoday, $verbose); +$p->process(); diff --git a/lib/copy_this/misc/testing/updateviddef.php b/lib/copy_this/misc/testing/updateviddef.php new file mode 100644 index 000000000..75ce22ab9 --- /dev/null +++ b/lib/copy_this/misc/testing/updateviddef.php @@ -0,0 +1 @@ +<?php define('FS_ROOT', realpath(dirname(__FILE__))); use newznab\db\DB; $r = new Releases(); $rv = new ReleaseExtra(); $db = new DB(); $rels = $db->query("select releaseID, videowidth, videoheight from releasevideo where definition is null"); foreach($rels as $rel) { $sql = sprintf("update releasevideo set definition = %d where releaseID = %d", $rv->determineVideoResolution($rel["videowidth"], $rel["videoheight"]), $rel["releaseID"]); $db->exec($sql); } ?> \ No newline at end of file diff --git a/lib/copy_this/misc/update_scripts/README.txt b/lib/copy_this/misc/update_scripts/README.txt new file mode 100644 index 000000000..2762c96be --- /dev/null +++ b/lib/copy_this/misc/update_scripts/README.txt @@ -0,0 +1,79 @@ +Update Scripts +============== + +This directory (``misc/update_scripts``) contains a collection of +command-line utilities for updating Newznab. Whilst you can run them stand-alone +for testing things out, it is intended that you should run the calling script +win_scripts\runme.bat or nix_scripts\newznab_screen.sh which runs each of these +scripts in the right order. + + +Updating +-------- + +These scripts should be run on a frequent basis in order to stay +current with the newest posts to usenet. + +``update_binaries.php`` +~~~~~~~~~~~~~~~~~~~~~~~ + +This script downloads new headers from the news server and puts them +in the database (binaries and parts tables). + +``update_binaries_threaded.php`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +This script runs on linux only and calls the update_binaries script in 10 +separate threads. + +``update_releases.php`` +~~~~~~~~~~~~~~~~~~~~~~~ + +This script creates releases from downloaded headers. It includes all the +additional post processing which is performed as a release is formed. + +``update_theaters.php`` +~~~~~~~~~~~~~~~~~~~~~~~ + +This script updates the 'whats on in theaters' data from rotten tomatoes if +a rotten tomatoes api key is present. + +``update_tvschedule.php`` +~~~~~~~~~~~~~~~~~~~~~~~~~ + +This script updates the tv schedule data from thetvdb. + +``import.php`` +~~~~~~~~~~~~~~~~~~~~~~~ + +This script is used for importing .nzb files from a path into newznab. + +Maintenance +----------- + +These scripts should be run occasionally. + +``optimise_db.php`` +~~~~~~~~~~~~~~~~~~~ + +Optimises and repairs mysql tables if necessary. Pass in the true argument to +force an optimise and repair regardless of whether its necessary. + +Backfilling +----------- + +``backfill.php`` +~~~~~~~~~~~~~~~~ + +The equivalent of ``update_binaries.php`` but for going forwards from the group.backfilldays to +the latest post. Downloads headers from usenet and puts them in the database (binaries and parts tables). + +``backfill_date.php`` +~~~~~~~~~~~~~~~~~~~~~ + +The same as ``backfill.php`` but goes back to a specific date passed as an argument. + +``backfill_threaded.php`` +~~~~~~~~~~~~~~~~~~~~~~~~~ + +Calls ``backfill.php`` with a thread for each group requiring backfilling. diff --git a/lib/copy_this/misc/update_scripts/backfill.php b/lib/copy_this/misc/update_scripts/backfill.php index 6748ad0f7..0cc514e59 100644 --- a/lib/copy_this/misc/update_scripts/backfill.php +++ b/lib/copy_this/misc/update_scripts/backfill.php @@ -1,8 +1,7 @@ <?php require_once("config.php"); -require_once(WWW_DIR . "/lib/framework/db.php"); -require_once(WWW_DIR."/lib/backfill.php"); -require_once(WWW_DIR . "/lib/nntp.php"); + +use newznab\db\DB; $pdo = new DB(); diff --git a/lib/copy_this/misc/update_scripts/backfill_date.php b/lib/copy_this/misc/update_scripts/backfill_date.php new file mode 100644 index 000000000..bcecc1b94 --- /dev/null +++ b/lib/copy_this/misc/update_scripts/backfill_date.php @@ -0,0 +1,45 @@ +<?php +/* + DESCRIPTION: + This script is an alternative to backfill.php. + It allows you to backfill based on a specific date, bypassing + the "backfill target" setting for each group, used by backfill.php + + PURPOSE: + If you are backfilling many groups over a long span of time, the # of days + set as your backfill target can become quickly outdated, resulting in + potential gaps in your database. In this case, it may be more practical + to specify a date explicity and just let the backfill work from there. + + USAGE: + $ php backfill_date.php 2011-05-15 + => Script will backfill ALL active groups from May 15, 2011 + + $ php backfill_date.php 2011-05-15 alt.binaries.games.xbox + => Script will backfill ONLY a.b.games.xbox from May 15, 2011 +*/ + +require("config.php"); + +$time = 0; + +if (isset($argv[1])) + $time = strtotime($argv[1]); + +if (($time > 1) && ($time < time())) { + $groupName = (isset($argv[2]) ? $argv[2] : ''); + + if (isset($argv[3]) && $argv[3] == true) + $regexOnly = true; + else + $regexOnly = false; + + $backfill = new Backfill(); + $backfill->backfillAllGroups($groupName, strtotime($argv[1]), $regexOnly); +} else { + echo "You must provide a backfill date in the format YYYY-MM-DD to use backfill_date.php\n"; + echo "example: backfill_date.php 2002-04-27 alt.binaries.games.xbox true\n"; + echo "This will backfill your index with everything posted to a.b.g.x since April 27, 2002 that matches system regex\n"; + echo "If you choose not to provide a groupname, all active groups will be backfilled.\n"; + echo "\nIf you do not want to use a date, use the backfill.php script instead.\n"; +} \ No newline at end of file diff --git a/lib/copy_this/misc/update_scripts/backfill_threaded.php b/lib/copy_this/misc/update_scripts/backfill_threaded.php new file mode 100644 index 000000000..469acf840 --- /dev/null +++ b/lib/copy_this/misc/update_scripts/backfill_threaded.php @@ -0,0 +1,73 @@ +<?php +require("config.php"); + +$groups = new \Groups; +$groupList = $groups->getActive(); +unset($groups); + +$ps = new \PowerProcess; +$ps->RegisterCallback('psUpdateComplete'); +$ps->maxThreads = 10; +$ps->tickCount = 10000; // value in usecs. change this to 1000000 (one second) to reduce cpu use +$ps->threadTimeLimit = 0; // Disable child timeout + +echo "Starting threaded backfill process\n"; + +while ($ps->RunControlCode()) +{ + // Start the parent loop + if (count($groupList)) + { + // We still have groups to process + if ($ps->SpawnReady()) + { + // Spawn another thread + $ps->threadData = array_pop($groupList); + echo "[Thread-MASTER] Spawning new thread. Still have " . count($groupList) ." group(s) to update after this\n"; + $ps->spawnThread(); + } + else + { + // There are no more slots available to run + //$ps->tick(); + //echo ".\n"; + } + } + else + { + // No more groups to process + echo "No more groups to process - Initiating shutdown\n"; + $ps->Shutdown(); + echo "Shutdown complete\n"; + } +} + +unset($groupList); + +if ($ps->RunThreadCode()) +{ + $group = $ps->threadData; + + $thread = sprintf("%05d",$ps->GetPID()); + + echo "[Thread-{$thread}] Begining backfill processing for group {$group['name']}\n"; + + $param = $group['name']; + + $dir = dirname(__FILE__); + $file = 'backfill.php'; + + $output = shell_exec("php {$dir}/{$file} {$param}"); + //$output = shell_exec("/usr/bin/php -c /etc/php5/cli/php.ini {$dir}/{$file} {$param}"); + + echo "[Thread-{$thread}] Completed update for group {$group['name']}\n"; +} + +// Exit to call back to parent - Let know that child has completed +exit(0); + +// Create callback function +function psUpdateComplete() +{ + echo "[Thread-MASTER] Threaded backfill process complete\n"; +} \ No newline at end of file diff --git a/lib/copy_this/misc/update_scripts/import.php b/lib/copy_this/misc/update_scripts/import.php index bd322ba4c..bb573abce 100644 --- a/lib/copy_this/misc/update_scripts/import.php +++ b/lib/copy_this/misc/update_scripts/import.php @@ -1,15 +1,12 @@ <?php define('FS_ROOT', realpath(dirname(__FILE__))); -require_once(FS_ROOT . "/../../www/lib/framework/db.php"); -require_once(FS_ROOT . "/../../www/lib/releases.php"); -require_once(FS_ROOT . "/../../www/lib/nzbinfo.php"); -require_once(FS_ROOT . "/../../www/lib/util.php"); -require_once(FS_ROOT . "/../../www/lib/nzb.php"); -require_once(FS_ROOT . "/../../www/lib/category.php"); + +use newznab\db\DB; +use newznab\utility\Utility; $releases = new Releases(); -$db = new Db(); +$db = new newznab\db\DB(); $cat = new Category(); $releaseRegex = new ReleaseRegex(); $nzb = new NZB(); @@ -23,7 +20,7 @@ $categoryoverride = -1; if (empty($argc) || $argc <= 1) { $path = "./"; } else { - $util = new Utility(); + $util = new newznab\utility\Utility(); $path = (!$util->endsWith($argv[1], "/") ? $argv[1] . "/" : $argv[1]); if (isset($argv[2])) $usefilename = strtolower($argv[2]) == 'true'; @@ -151,7 +148,7 @@ foreach ($filestoprocess as $nzbFile) { $db->escapeString(md5($postFile["subject"] . $postFile["poster"] . $groupID)), $regexMatches['regcatid'], $regexMatches['regexid'], $db->escapeString($regexMatches['reqid']), - Releases::PROCSTAT_TITLEMATCHED, $relparts[0], $relparts[1], $db->escapeString(str_replace('_', ' ', $regexMatches['name'])) + \Releases::PROCSTAT_TITLEMATCHED, $relparts[0], $relparts[1], $db->escapeString(str_replace('_', ' ', $regexMatches['name'])) ); $binaryId = $db->queryInsert($sql); $numbins++; diff --git a/lib/copy_this/misc/update_scripts/nix_scripts/README.txt b/lib/copy_this/misc/update_scripts/nix_scripts/README.txt new file mode 100644 index 000000000..a1816cf37 --- /dev/null +++ b/lib/copy_this/misc/update_scripts/nix_scripts/README.txt @@ -0,0 +1,20 @@ +Inlcuded in this folder are init.d scripts for unix users. These are NOT to be cronned. +They must be ran by init.d or in a screen. + +You MUST set the paths to where you have installed newznab. + +The recommended way to run script is via screen. You should copy newznab_screen.sh +to newznab_local.sh so that when you svn update (or export), your changes are not lost. + +Detailed instructions... + +cp newznab_screen.sh newznab_local.sh +edit newznab_local.sh to specify paths to your installation +chmod +x newznab_local.sh +screen bash +./newznab_local.sh +ctrl-ad to detach screen + + + +This will update binaries and releases in a continuous cycle. \ No newline at end of file diff --git a/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/.do_not_run/switch.php b/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/.do_not_run/switch.php index 22ce15d7d..9bbc3d639 100644 --- a/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/.do_not_run/switch.php +++ b/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/.do_not_run/switch.php @@ -5,16 +5,11 @@ if (!isset($argv[1])) { } require_once dirname(__FILE__) . '/../../../../../www/config.php'; -require_once(WWW_DIR . "/lib/framework/db.php"); -require_once(WWW_DIR . "/lib/binaries.php"); -require_once(WWW_DIR . "/lib/releases.php"); -require_once(WWW_DIR . "/lib/groups.php"); -require_once(WWW_DIR . "/lib/backfill.php"); -require_once(WWW_DIR . "/lib/nntp.php"); -require_once(WWW_DIR . "/lib/site.php"); -require_once(WWW_DIR . "/processing/ProcessReleases.php"); -require_once(NN_LIB . 'RequestIDLocal.php'); +use \newznab\db\DB; +use \newznab\processing\PProcess; +use \newznab\processing\ProcessReleases; +use \newznab\processing\post\ProcessAdditional; // Are we coming from python or php ? $options[0] => (string): python|php // The type of process we want to do: $options[1] => (string): releases @@ -27,7 +22,7 @@ switch ($options[1]) { // $options[3] => (int) backfill type from tmux settings. 1 = Backfill interval , 2 = Bakfill all case 'backfill': if (in_array((int)$options[3], [1, 2])) { - $pdo = new \DB(); + $pdo = new DB(); $value = $pdo->queryOneRow("SELECT value FROM tmux WHERE setting = 'backfill_qty'"); if ($value !== false) { $nntp = nntp($pdo); @@ -42,7 +37,7 @@ switch ($options[1]) { * $options[3] => (int) Quantity of articles to download. */ case 'backfill_all_quantity': - $pdo = new \DB(); + $pdo = new DB(); $nntp = nntp($pdo); (new \Backfill())->backfillAllGroups($options[2], $options[3]); break; @@ -50,7 +45,7 @@ switch ($options[1]) { // BackFill a single group, 10000 parts. // $options[2] => (string)group name, Name of group to work on. case 'backfill_all_quick': - $pdo = new \DB(); + $pdo = new DB(); $nntp = nntp($pdo); (new \Backfill())->backfillAllGroups($options[2], 10000, 'normal'); break; @@ -64,7 +59,7 @@ switch ($options[1]) { * $options[6] => (int) Number of threads. */ case 'get_range': - $pdo = new \DB(); + $pdo = new DB(); $nntp = nntp($pdo); $groups = new \Groups(); $s = new Sites(); @@ -131,7 +126,7 @@ switch ($options[1]) { * $options[2] => (string) Group name. */ case 'part_repair': - $pdo = new \DB(); + $pdo = new DB(); $groups = new \Groups(['Settings' => $pdo]); $groupMySQL = $groups->getByName($options[2]); $nntp = nntp($pdo); @@ -148,7 +143,7 @@ switch ($options[1]) { // Process releases. // $options[2] => (string)groupCount, number of groups terminated by _ | (int)groupid, group to work on case 'releases': - $pdo = new \DB(); + $pdo = new DB(); $releases = new ProcessReleases(['Settings' => $pdo]); //Runs function that are per group @@ -188,7 +183,7 @@ switch ($options[1]) { * $options[2] => (string) Group name. */ case 'update_group_headers': - $pdo = new \DB(); + $pdo = new DB(); $nntp = nntp($pdo); $groups = new \Groups(); $groupMySQL = $groups->getByName($options[2]); @@ -201,7 +196,7 @@ switch ($options[1]) { case 'update_per_group': if (is_numeric($options[2])) { - $pdo = new \DB(); + $pdo = new DB(); // Get the group info from MySQL. $groupMySQL = $pdo->queryOneRow(sprintf('SELECT * FROM groups WHERE id = %d', $options[2])); @@ -224,7 +219,7 @@ switch ($options[1]) { processReleases(new \Releases(['Settings' => $pdo]), $options[2]); // Post process the releases. - (new \ProcessAdditional(['Echo' => true, 'NNTP' => $nntp, 'Settings' => $pdo]))->start($options[2]); + (new ProcessAdditional(['Echo' => true, 'NNTP' => $nntp, 'Settings' => $pdo]))->start($options[2]); (new \Info(['Echo' => true, 'Settings' => $pdo]))->processNfoFiles($nntp, $options[2]); } @@ -235,7 +230,7 @@ switch ($options[1]) { case 'pp_additional': case 'pp_nfo': if (charCheck($options[2])) { - $pdo = new \DB(); + $pdo = new DB(); // Create the connection here and pass, this is for post processing, so check for alternate. $nntp = nntp($pdo, true); @@ -243,7 +238,7 @@ switch ($options[1]) { if ($options[1] === 'pp_nfo') { (new \Info(['Echo' => true, 'Settings' => $pdo]))->processNfoFiles($nntp, '', $options[2]); } else { - (new \ProcessAdditional(['Echo' => true, 'NNTP' => $nntp, 'Settings' => $pdo]))->start('', $options[2]); + (new ProcessAdditional(['Echo' => true, 'NNTP' => $nntp, 'Settings' => $pdo]))->start('', $options[2]); } } break; @@ -255,8 +250,8 @@ switch ($options[1]) { */ case 'pp_movie': if (charCheck($options[2])) { - $pdo = new \DB(); - (new \PProcess(['Settings' => $pdo]))->processMovies('', $options[2], (isset($options[3]) ? $options[3] : '')); + $pdo = new DB(); + (new PProcess(['Settings' => $pdo]))->processMovies('', $options[2], (isset($options[3]) ? $options[3] : '')); } break; @@ -267,8 +262,8 @@ switch ($options[1]) { */ case 'pp_tv': if (charCheck($options[2])) { - $pdo = new \DB(); - (new \PProcess(['Settings' => $pdo]))->processTv('', $options[2], (isset($options[3]) ? $options[3] : '')); + $pdo = new DB(); + (new PProcess(['Settings' => $pdo]))->processTv('', $options[2], (isset($options[3]) ? $options[3] : '')); } break; } @@ -276,7 +271,7 @@ switch ($options[1]) { /** * Create / process releases for a groupid. * - * @param \ProcessReleases $releases + * @param \newznab\processing\ProcessReleases $releases * @param int $groupID */ function processReleases($releases, $groupID) @@ -307,7 +302,7 @@ function charCheck($char) /** * Check if the group should be processed. * - * @param \DB $pdo + * @param \newznab\db\DB $pdo * @param int $groupID */ function collectionCheck(&$pdo, $groupID) @@ -320,7 +315,7 @@ function collectionCheck(&$pdo, $groupID) /** * Connect to usenet, return NNTP object. * - * @param \DB $pdo + * @param \newznab\db\DB $pdo * @param bool $alternate Use alternate NNTP provider. * * @return NNTP @@ -335,4 +330,4 @@ function &nntp(&$pdo, $alternate = false) } return $nntp; -} +} \ No newline at end of file diff --git a/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/backfill.php b/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/backfill.php index b43e5edc7..8e42089f6 100644 --- a/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/backfill.php +++ b/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/backfill.php @@ -1,8 +1,8 @@ <?php declare(ticks=1); require('.do_not_run/require.php'); -require_once('Forking.php'); +use newznab\libraries\Forking; // Check if argument 1 is numeric, which is to limit article count. -(new \Forking())->processWorkType( +(new Forking())->processWorkType( 'backfill', (isset($argv[1]) && is_numeric($argv[1]) && $argv[1] > 0 ? array(0 => $argv[1]) : array(0 => false)) ); \ No newline at end of file diff --git a/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/binaries.php b/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/binaries.php index 70826294d..f02ee7c6a 100644 --- a/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/binaries.php +++ b/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/binaries.php @@ -6,5 +6,5 @@ if (!isset($argv[1]) || !is_numeric($argv[1])) { } declare(ticks=1); require('.do_not_run/require.php'); -require_once('Forking.php'); -(new \Forking())->processWorkType('binaries', array(0 => $argv[1])); \ No newline at end of file +use newznab\libraries\Forking; +(new Forking())->processWorkType('binaries', array(0 => $argv[1])); \ No newline at end of file diff --git a/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/fixrelnames.php b/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/fixrelnames.php index f06853b83..4598619de 100644 --- a/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/fixrelnames.php +++ b/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/fixrelnames.php @@ -13,5 +13,8 @@ if (!isset($argv[1]) || !in_array($argv[1], ['nfo', 'filename', 'md5', 'par2', ' declare(ticks=1); require('.do_not_run/require.php'); -require_once('Forking.php'); -(new \Forking())->processWorkType('fixRelNames_' . $argv[1], [0 => $argv[1]]); + +use newznab\libraries\Forking; + + +(new Forking())->processWorkType('fixRelNames_' . $argv[1], [0 => $argv[1]]); diff --git a/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/import.php b/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/import.php index d90a8fdc7..c7ee70c60 100644 --- a/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/import.php +++ b/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/import.php @@ -1,7 +1,8 @@ <?php declare(ticks=1); require('.do_not_run/require.php'); -require_once('ForkingImportNZB.php'); + +use newznab\libraries\ForkingImportNZB; if (!isset($argv[1]) || !is_dir($argv[1])) { exit( @@ -23,7 +24,7 @@ if (!isset($argv[1]) || !is_dir($argv[1])) { ); } -(new \ForkingImportNZB())->start( +(new ForkingImportNZB())->start( $argv[1], (isset($argv[2]) && is_numeric($argv[2]) && $argv[2] > 0 ? $argv[2] : 1), (isset($argv[3]) && $argv[3] === 'true' ? 'true' : 'false'), diff --git a/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/postprocess.php b/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/postprocess.php index a3fc8c50c..f9b8a0039 100644 --- a/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/postprocess.php +++ b/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/postprocess.php @@ -15,5 +15,7 @@ if (!isset($argv[1]) || !in_array($argv[1], ['ama', 'add', 'mov', 'nfo', 'sha', declare(ticks=1); require('.do_not_run/require.php'); -require_once('Forking.php'); -(new \Forking())->processWorkType('postProcess_' . $argv[1], (isset($argv[2]) && $argv[2] === 'true' ? [0 => true] : [])); \ No newline at end of file + +use newznab\libraries\Forking; + +(new Forking())->processWorkType('postProcess_' . $argv[1], (isset($argv[2]) && $argv[2] === 'true' ? [0 => true] : [])); \ No newline at end of file diff --git a/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/releases.php b/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/releases.php index c8bfd87bd..b3eb9964e 100644 --- a/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/releases.php +++ b/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/releases.php @@ -1,5 +1,7 @@ <?php declare(ticks=1); require('.do_not_run/require.php'); -require_once('Forking.php'); -(new \Forking())->processWorkType('releases'); \ No newline at end of file + +use newznab\libraries\Forking; + +(new Forking())->processWorkType('releases'); \ No newline at end of file diff --git a/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/requestid.php b/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/requestid.php index 98510074c..9de63e411 100644 --- a/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/requestid.php +++ b/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/requestid.php @@ -1,5 +1,7 @@ <?php declare(ticks=1); require('.do_not_run/require.php'); -require_once('Forking.php'); -(new \Forking())->processWorkType('request_id'); \ No newline at end of file + +use \newznab\libraries\Forking; + +(new Forking())->processWorkType('request_id'); \ No newline at end of file diff --git a/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/safe.php b/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/safe.php index 995ca9074..a7f7c6601 100644 --- a/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/safe.php +++ b/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/safe.php @@ -9,5 +9,7 @@ if (!isset($argv[1]) || !in_array($argv[1], ['backfill', 'binaries'])) { declare(ticks=1); require('.do_not_run/require.php'); -require_once('Forking.php'); -(new \Forking())->processWorkType('safe_' . $argv[1]); + +use \newznab\libraries\Forking; + +(new Forking())->processWorkType('safe_' . $argv[1]); diff --git a/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/update_per_group.php b/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/update_per_group.php index 387129ca5..316b2773a 100644 --- a/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/update_per_group.php +++ b/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/update_per_group.php @@ -1,6 +1,8 @@ <?php declare(ticks=1); require('.do_not_run/require.php'); -require_once('Forking.php'); + +use \newznab\libraries\Forking; + // This is the same as the python update_threaded.php -(new \Forking())->processWorkType('update_per_group'); \ No newline at end of file +(new Forking())->processWorkType('update_per_group'); \ No newline at end of file diff --git a/lib/copy_this/misc/update_scripts/nix_scripts/newznab.sh b/lib/copy_this/misc/update_scripts/nix_scripts/newznab.sh new file mode 100644 index 000000000..83b740766 --- /dev/null +++ b/lib/copy_this/misc/update_scripts/nix_scripts/newznab.sh @@ -0,0 +1,88 @@ +#!/bin/sh +# +# /etc/init.d/newznab: start and stop the newznab update script +# +# run update-rc.d newznab_ubuntu.sh defaults + + +### BEGIN INIT INFO +# Provides: Newznab +# Required-Start: $remote_fs $syslog +# Required-Stop: $remote_fs $syslog +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Start newznab at boot time +# Description: Enable newznab service provided by daemon. +### END INIT INFO + +RED=$(tput setaf 1) +GREEN=$(tput setaf 2) +NORMAL=$(tput sgr0) + +col=40 + +# Newznab variables + +NN_PATH="/var/www/newznab/htdocs/misc/update_scripts" +NN_BINUP="update_binaries.php" +NN_RELUP="update_releases.php" +NN_PREDB="update_predb.php true" +NN_OPT="optimise_db.php" +NN_TV="update_tvschedule.php" +NN_THEATERS="update_theaters.php" +NN_SLEEP_TIME="10" # in seconds . 10sec is good for 100s of groups. 600sec might be a good start for fewer. +NN_PID_PATH="/var/run/" +PIDFILE="newznab_sh.pid" +LASTOPTIMIZE=`date +%s` + +test -f /lib/lsb/init-functions || exit 1 +. /lib/lsb/init-functions + +case "$1" in + start) + if [ -f ${NN_PID_PATH}${PIDFILE} ] + then + echo "$0 is already running." + else + echo -n "Starting Newznab binaries update..." + cd ${NN_PATH} + while : + do + CURRTIME=`date +%s` + php ${NN_BINUP} 2>&1 > /dev/null && php ${NN_RELUP} 2>&1 > /dev/null && php ${NN_PREDB} 2>&1 > /dev/null + DIFF=$(($CURRTIME-$LASTOPTIMIZE)) + if [ "$DIFF" -gt 43200 ] || [ "$DIFF" -lt 1 ] + then + LASTOPTIMIZE=`date +%s` + php ${NN_OPT} 2>&1 > /dev/null && php ${NN_TV} 2>&1 > /dev/null && php ${NN_THEATERS} 2>&1 > /dev/null + fi + sleep ${NN_SLEEP_TIME} + done & + PID=$! + echo $PID > ${NN_PID_PATH}${PIDFILE} + sleep 2 + if [ -f ${NN_PID_PATH}${PIDFILE} ] + then + printf '%s%*s%s\n' "$GREEN" $col '[OK]' "$NORMAL" + else + printf '%s%*s%s\n' "$RED" $col '[FAIL]' "$NORMAL" + fi + fi & + ;; + stop) + echo -n "Stopping Newznab binaries update..." + kill -9 `cat ${NN_PID_PATH}${PIDFILE}` && kill -9 `cat ${NN_PID_PATH}${PIDFILE}` && rm ${NN_PID_PATH}${PIDFILE} + sleep 2 + if [ -f ${NN_PID_PATH}${PIDFILE} ] + then + printf '%s%*s%s\n' "$RED" $col '[FAIL]' "$NORMAL" + else + printf '%s%*s%s\n' "$GREEN" $col '[OK]' "$NORMAL" + fi + ;; + + *) + echo "Usage: $0 [start|stop]" + exit 1 +esac + diff --git a/lib/copy_this/misc/update_scripts/nix_scripts/newznab_screen.sh b/lib/copy_this/misc/update_scripts/nix_scripts/newznab_screen.sh new file mode 100644 index 000000000..a5f8ce255 --- /dev/null +++ b/lib/copy_this/misc/update_scripts/nix_scripts/newznab_screen.sh @@ -0,0 +1,31 @@ +#!/bin/sh +# call this script from within screen to get binaries, processes releases and +# every half day get tv/theatre info and optimise the database + +set -e + +export NEWZNAB_PATH="/usr/local/www/newznab/misc/update_scripts" +export NEWZNAB_SLEEP_TIME="600" # in seconds +LASTOPTIMIZE=`date +%s` + +while : + + do +CURRTIME=`date +%s` +cd ${NEWZNAB_PATH} +/usr/bin/php5 ${NEWZNAB_PATH}/update_binaries.php +/usr/bin/php5 ${NEWZNAB_PATH}/update_releases.php + +DIFF=$(($CURRTIME-$LASTOPTIMIZE)) +if [ "$DIFF" -gt 43200 ] || [ "$DIFF" -lt 1 ] +then + LASTOPTIMIZE=`date +%s` + /usr/bin/php5 ${NEWZNAB_PATH}/optimise_db.php + /usr/bin/php5 ${NEWZNAB_PATH}/update_tvschedule.php + /usr/bin/php5 ${NEWZNAB_PATH}/update_theaters.php +fi + +echo "waiting ${NEWZNAB_SLEEP_TIME} seconds..." +sleep ${NEWZNAB_SLEEP_TIME} + +done diff --git a/lib/copy_this/misc/update_scripts/nix_scripts/newznab_ubuntu.sh b/lib/copy_this/misc/update_scripts/nix_scripts/newznab_ubuntu.sh new file mode 100644 index 000000000..235a6149c --- /dev/null +++ b/lib/copy_this/misc/update_scripts/nix_scripts/newznab_ubuntu.sh @@ -0,0 +1,51 @@ +#!/bin/sh +# +# Ian - 16/11/2011 +# /etc/init.d/newznab: start and stop the newznab update script +# +# run update-rc.d newznab_ubuntu.sh defaults + + +### BEGIN INIT INFO +# Provides: Newznab +# Required-Start: $remote_fs $syslog +# Required-Stop: $remote_fs $syslog +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Start newznab at boot time +# Description: Enable newznab service provided by daemon. +### END INIT INFO + + +# Newznab variables +NN_PATH="/var/www/newznab/misc/update_scripts" +NN_BINUP="update_binaries.php" +NN_RELUP="update_releases.php" +NN_SLEEP_TIME="600" # in seconds . 10sec is good for 100s of groups. 600sec might be a good start for fewer. +NN_PID_PATH="/var/run/" +PIDFILE="newznab_binup.pid" + +test -f /lib/lsb/init-functions || exit 1 +. /lib/lsb/init-functions + + + +case "$1" in + start) + [ -f ${NN_PID_PATH}${PIDFILE} ] && { echo "$0 is already ruNNing."; false; } + echo -n "Starting Newznab binaries update" + cd ${NN_PATH} + (while (true);do cd ${NN_PATH} && php ${NN_BINUP} 2>&1 > /dev/null && php ${NN_RELUP} 2>&1 > /dev/null ; sleep ${NN_SLEEP_TIME} ;done) & + PID=`echo $!` + echo $PID > ${NN_PID_PATH}${PIDFILE} + ;; + stop) + echo -n "Stopping Newznab binaries update" + kill -9 `cat ${NN_PID_PATH}${PIDFILE}` + ;; + + *) + echo "Usage: $0 [start|stop]" + exit 1 +esac + diff --git a/lib/copy_this/misc/update_scripts/nntpproxy.php b/lib/copy_this/misc/update_scripts/nntpproxy.php index f487dd95b..4f08c9af0 100644 --- a/lib/copy_this/misc/update_scripts/nntpproxy.php +++ b/lib/copy_this/misc/update_scripts/nntpproxy.php @@ -1,8 +1,7 @@ <?php require_once("config.php"); -require_once(WWW_DIR . "/lib/framework/db.php"); -require_once(WWW_DIR . "/lib/Tmux.php"); -require_once(WWW_DIR . "/lib/site.php"); + +use newznab\db\DB; passthru("clear"); diff --git a/lib/copy_this/misc/update_scripts/optimise_db.php b/lib/copy_this/misc/update_scripts/optimise_db.php new file mode 100644 index 000000000..d930aa210 --- /dev/null +++ b/lib/copy_this/misc/update_scripts/optimise_db.php @@ -0,0 +1,19 @@ +<?php + +require("config.php"); + +use newznab\db\DB; + +$force = ((isset($argv[1]) && ($argv[1] == "true"))); + +$db = new DB; +$ret = $db->optimise($force); + +if (count($ret) > 0) +{ + echo "Optmze : Optimised ".count($ret)." tables\n"; +} +else +{ + echo "Optmze : Nothing required optimisation.".(!$force ? " Try using force (optimise_db.php true)" : "")."\n"; +} \ No newline at end of file diff --git a/lib/copy_this/misc/update_scripts/update_binaries.php b/lib/copy_this/misc/update_scripts/update_binaries.php index 551113ae6..18465423c 100644 --- a/lib/copy_this/misc/update_scripts/update_binaries.php +++ b/lib/copy_this/misc/update_scripts/update_binaries.php @@ -1,9 +1,8 @@ <?php require_once(dirname(__FILE__) . "/config.php"); -require_once(WWW_DIR."/lib/groups.php"); -require_once(WWW_DIR."/lib/binaries.php"); -require_once(WWW_DIR."/lib/nntp.php"); + +use newznab\db\DB; $pdo = new DB(); diff --git a/lib/copy_this/misc/update_scripts/update_binaries_threaded.php b/lib/copy_this/misc/update_scripts/update_binaries_threaded.php new file mode 100644 index 000000000..305157492 --- /dev/null +++ b/lib/copy_this/misc/update_scripts/update_binaries_threaded.php @@ -0,0 +1,75 @@ +<?php + +$groups = new Groups; +$groupList = $groups->getActive(); +unset($groups); + +$ps = new PowerProcess; +$ps->RegisterCallback('psUpdateComplete'); +$ps->maxThreads = 10; +$ps->tickCount = 10000; // value in usecs. change this to 1000000 (one second) to reduce cpu use +$ps->threadTimeLimit = 0; // Disable child timeout + +echo "Starting threaded binary update process\n"; + +//while ($ps->runParentCode()) +while ($ps->RunControlCode()) +{ + // Start the parent loop + if (count($groupList)) + { + // We still have groups to process + if ($ps->SpawnReady()) + { + // Spawn another thread + $ps->threadData = array_pop($groupList); + echo "[Thread-MASTER] Spawning new thread. Still have " . count($groupList) ." group(s) to update after this\n"; + $ps->spawnThread(); + } + else + { + // There are no more slots available to run + //$ps->tick(); + //echo "- \n"; + } + } + else + { + // No more groups to process + echo "No more groups to process - Initiating shutdown\n"; + $ps->Shutdown(); + echo "Shutdown complete\n"; + } +} + +unset($groupList); + +if ($ps->RunThreadCode()) +{ + $group = $ps->threadData; + + $thread = sprintf("%05d",$ps->GetPID()); + + echo "[Thread-{$thread}] Begining processing for group {$group['name']}\n"; + + $param = $group['name']; + + $dir = dirname(__FILE__); + $file = 'update_binaries.php'; + + $output = shell_exec("php {$dir}/{$file} {$param}"); + //$output = shell_exec("/usr/bin/php -c /etc/php5/cli/php.ini {$dir}/{$file} {$param}"); + + echo "[Thread-{$thread}] Completed update for group {$group['name']}\n"; +} + +// Exit to call back to parent - Let know that child has completed +exit(0); + + + +// Create callback function +function psUpdateComplete() +{ + echo "Threaded update process complete\n"; +} \ No newline at end of file diff --git a/lib/copy_this/misc/update_scripts/update_database_version.php b/lib/copy_this/misc/update_scripts/update_database_version.php new file mode 100644 index 000000000..a1eab0683 --- /dev/null +++ b/lib/copy_this/misc/update_scripts/update_database_version.php @@ -0,0 +1,37 @@ +<?php + +require("./config.php"); + +use newznab\db\DB; + +$s = new Sites(); +$site = $s->get(); +$patches = $s->getUnappliedPatches($site); + +if (count($patches) == 0) + echo "Patchn : No patches required applying. At version ".$site->dbversion."\n"; +else +{ + echo "Patchn : Database at version ".$site->dbversion."\n"; + + foreach ($patches as $patch) + { + echo "Patchn : Executing patch ".basename($patch)."\n"; + + $db = new DB(); + $rows = $db->query("select * from site"); + + $dbData = file_get_contents($patch); + //fix to remove BOM in UTF8 files + $bom = pack("CCC", 0xef, 0xbb, 0xbf); + if (0 == strncmp($dbData, $bom, 3)) { + $dbData = substr($dbData, 3); + } + $queries = explode(";", $dbData); + $queries = array_map("trim", $queries); + foreach($queries as $q) { + if (strlen($q) > 0) + $db->exec($q); + } + } +} \ No newline at end of file diff --git a/lib/copy_this/misc/update_scripts/update_predb.php b/lib/copy_this/misc/update_scripts/update_predb.php new file mode 100644 index 000000000..56e820e0e --- /dev/null +++ b/lib/copy_this/misc/update_scripts/update_predb.php @@ -0,0 +1,6 @@ +<?php + +$p = new PreDB(true); +$p->nzpreUpdate(); +if(isset($argv[1]) && $argv[1] == true) + $p->processReleases($daysback=(isset($argv[2]) ? $argv[2] : 3)); \ No newline at end of file diff --git a/lib/copy_this/misc/update_scripts/update_releases.php b/lib/copy_this/misc/update_scripts/update_releases.php new file mode 100644 index 000000000..f37b0e54b --- /dev/null +++ b/lib/copy_this/misc/update_scripts/update_releases.php @@ -0,0 +1,8 @@ +<?php + +require("config.php"); + +$releases = new Releases; +$sphinx = new Sphinx(); +$releases->processReleases(); +$sphinx->update(); diff --git a/lib/copy_this/misc/update_scripts/update_theaters.php b/lib/copy_this/misc/update_scripts/update_theaters.php index 3604ea946..ffa721d86 100644 --- a/lib/copy_this/misc/update_scripts/update_theaters.php +++ b/lib/copy_this/misc/update_scripts/update_theaters.php @@ -1,7 +1,6 @@ <?php //run this once per day require_once("config.php"); -require_once(WWW_DIR.'/../misc/update_scripts/nix_scripts/tmux/lib/Film.php'); $m = new \Film(['Echo' => true]); $m->updateUpcoming(); diff --git a/lib/copy_this/misc/update_scripts/update_tvschedule.php b/lib/copy_this/misc/update_scripts/update_tvschedule.php index 6b1e92eed..e7e8d48a9 100644 --- a/lib/copy_this/misc/update_scripts/update_tvschedule.php +++ b/lib/copy_this/misc/update_scripts/update_tvschedule.php @@ -2,6 +2,5 @@ // Run this once per day. require_once("config.php"); -require_once(WWW_DIR.'/../misc/update_scripts/nix_scripts/tmux/lib/TvAnger.php'); (new \TvAnger(['Echo' => true]))->updateSchedule(); \ No newline at end of file diff --git a/lib/copy_this/misc/update_scripts/win_scripts/README.txt b/lib/copy_this/misc/update_scripts/win_scripts/README.txt new file mode 100644 index 000000000..70a53b340 --- /dev/null +++ b/lib/copy_this/misc/update_scripts/win_scripts/README.txt @@ -0,0 +1,11 @@ +Inlcuded in this folder are batch files for windows users. +You MUST set your system path to include the PHP path. + +Otherwise at the top of each batch file add the line +set Path=“C:\yourpathtoPHP\” + +updatebinaries.bat will execute the updatebinaries.php script. +updatereleases.bat will execute the updatereleases.php script. +updatebackill.bat will execute the backfill.php script. +Runme.bat will run a continous loop of update binaries and update releases and will optimise your db every 300 cycles. +Runme_with_scrape.bat is the same thing as Runme, however it will scrape every fifth time, if you are utilizing reqscraper. diff --git a/lib/copy_this/misc/update_scripts/win_scripts/Sleep.exe b/lib/copy_this/misc/update_scripts/win_scripts/Sleep.exe new file mode 100644 index 000000000..aebb998c1 Binary files /dev/null and b/lib/copy_this/misc/update_scripts/win_scripts/Sleep.exe differ diff --git a/lib/copy_this/misc/update_scripts/win_scripts/optimisedb.bat b/lib/copy_this/misc/update_scripts/win_scripts/optimisedb.bat new file mode 100644 index 000000000..5725fe2f3 --- /dev/null +++ b/lib/copy_this/misc/update_scripts/win_scripts/optimisedb.bat @@ -0,0 +1,3 @@ +CD.. +php.exe optimise_db.php true +quit \ No newline at end of file diff --git a/lib/copy_this/misc/update_scripts/win_scripts/runme.bat b/lib/copy_this/misc/update_scripts/win_scripts/runme.bat new file mode 100644 index 000000000..c0eee3817 --- /dev/null +++ b/lib/copy_this/misc/update_scripts/win_scripts/runme.bat @@ -0,0 +1,49 @@ +set optimise=1 + + +set limit=111111111111111111111111 + +:Top + +CD.. +php.exe update_database_version.php +php.exe update_binaries.php +php.exe update_releases.php +CD win_scripts + +set /a optimise=%optimise%+1 +if %optimise%==300 goto optimise +:OptimiseDone + +set /a tv=%tv%+1 +if %tv%==20 goto tv +:TVDone + +set /a Movies=%Movies%+1 +if %Movies%==20 goto Movies +:moviesDone + +Sleep 120 + +GOTO TOP + +:Optimise +CD.. +php.exe optimise_db.php +set optimise=0 +CD win_scripts +GOTO OptimiseDone + +:TV +CD.. +php.exe update_tvschedule.php +set tv=0 +CD win_scripts +GOTO tvdone + +:Movies +CD.. +php.exe update_theaters.php +set Movies=0 +CD win_scripts +GOTO Moviesdone \ No newline at end of file diff --git a/lib/copy_this/misc/update_scripts/win_scripts/runme_with_scrape.bat b/lib/copy_this/misc/update_scripts/win_scripts/runme_with_scrape.bat new file mode 100644 index 000000000..cbdd267d7 --- /dev/null +++ b/lib/copy_this/misc/update_scripts/win_scripts/runme_with_scrape.bat @@ -0,0 +1,64 @@ +set optimise=1 +set scrape=1 + +set limit=111111111111111111111111 + +:Top + +CD.. +php.exe update_database_version.php +php.exe update_binaries.php +php.exe update_releases.php +CD win_scripts + +set /a scrape=%scrape%+1 +if %scrape%==5 goto scrape +:ScrapeDone + +set /a optimise=%optimise%+1 +if %optimise%==300 goto optimise +:OptimiseDone + +set /a tv=%tv%+1 +if %tv%==20 goto tv +:TVDone + +set /a Movies=%Movies%+1 +if %Movies%==20 goto Movies +:moviesDone + +Sleep 120 + +GOTO TOP + +:Optimise +CD.. +php.exe optimise_db.php +set optimise=0 +CD win_scripts +GOTO OptimiseDone + +:Scrape +CD.. +CD.. +CD reqscraper +php scrape.php +set scrape=0 +CD.. +CD update_scripts +CD win_scripts +GOTO ScrapeDone + +:TV +CD.. +php.exe update_tvschedule.php +set tv=0 +CD win_scripts +GOTO tvdone + +:Movies +CD.. +php.exe update_theaters.php +set Movies=0 +CD win_scripts +GOTO Moviesdone \ No newline at end of file diff --git a/lib/copy_this/misc/update_scripts/win_scripts/updatebackfill.bat b/lib/copy_this/misc/update_scripts/win_scripts/updatebackfill.bat new file mode 100644 index 000000000..6c84f0cd2 --- /dev/null +++ b/lib/copy_this/misc/update_scripts/win_scripts/updatebackfill.bat @@ -0,0 +1,16 @@ +:Top +echo off +cls +:MAINMENU choose option from menu +set /p userinp=Enter the full group name you would like to backfill, or to default to all groups, simply press enter: +set userinp=%userinp% +if "%userinp%"=="" goto All + +:SINGLE +CD.. +php.exe backfill.php "%userinp%" + +:ALL +CD.. +php.exe backfill.php + diff --git a/lib/copy_this/misc/update_scripts/win_scripts/updatebinaries.bat b/lib/copy_this/misc/update_scripts/win_scripts/updatebinaries.bat new file mode 100644 index 000000000..250ea61ca --- /dev/null +++ b/lib/copy_this/misc/update_scripts/win_scripts/updatebinaries.bat @@ -0,0 +1,3 @@ +CD.. +php.exe update_binaries.php +quit \ No newline at end of file diff --git a/lib/copy_this/misc/update_scripts/win_scripts/updatereleases.bat b/lib/copy_this/misc/update_scripts/win_scripts/updatereleases.bat new file mode 100644 index 000000000..9a0990e6f --- /dev/null +++ b/lib/copy_this/misc/update_scripts/win_scripts/updatereleases.bat @@ -0,0 +1,3 @@ +CD.. +php.exe update_releases.php +quit \ No newline at end of file diff --git a/lib/copy_this/newznab/autoloader.php b/lib/copy_this/newznab/autoloader.php new file mode 100644 index 000000000..7b8bfc0be --- /dev/null +++ b/lib/copy_this/newznab/autoloader.php @@ -0,0 +1,50 @@ +<?php +if (file_exists(realpath(dirname(__DIR__)) . DIRECTORY_SEPARATOR . 'www' . DIRECTORY_SEPARATOR . 'config.php')) { + require_once realpath(dirname(__DIR__)) . DIRECTORY_SEPARATOR . 'www' . DIRECTORY_SEPARATOR . 'config.php'; +} + +/** + * An example of a project-specific implementation. + * + * After registering this autoload function with SPL, the following line + * would cause the function to attempt to load the \Foo\Bar\Baz\Qux class + * from /path/to/project/src/Baz/Qux.php: + * + * new \Foo\Bar\Baz\Qux; + * + * @param string $class The fully-qualified class name. + * @return void + */ +spl_autoload_register(function($class) { + + // project-specific namespace prefix + $prefix = 'newznab\\'; + + // base directory for the namespace prefix + $base_dir = __DIR__ . DIRECTORY_SEPARATOR; + + // If no namespace, add default; + $class = preg_match('#\\\#', $class) ? $class : $prefix . 'controllers\\' . $class; + + // does the class use the namespace prefix? + $len = strlen($prefix); + if (strncmp($prefix, $class, $len) !== 0) { + // no, move to the next registered autoloader + return; + } + + // get the relative class name + $relative_class = substr($class, $len); + + // replace the namespace prefix with the base directory, replace namespace + // separators with directory separators in the relative class name, append + // with .php + $file = $base_dir . str_replace('\\', DIRECTORY_SEPARATOR, $relative_class) . '.php'; + + // if the file exists, require it + if (file_exists($file)) { + require_once $file; + } elseif (NN_LOGAUTOLOADER) { + var_dump($file); + } +}); \ No newline at end of file diff --git a/lib/copy_this/www/lib/ADE.php b/lib/copy_this/newznab/controllers/ADE.php similarity index 99% rename from lib/copy_this/www/lib/ADE.php rename to lib/copy_this/newznab/controllers/ADE.php index ea2d80510..9f38d80a4 100644 --- a/lib/copy_this/www/lib/ADE.php +++ b/lib/copy_this/newznab/controllers/ADE.php @@ -1,7 +1,6 @@ <?php -require_once(WWW_DIR . "../misc/update_scripts/nix_scripts/tmux/lib/simple_html_dom.php"); - +require_once NN_LIBS . 'simple_html_dom.php'; /** * Class adultdvdempire */ diff --git a/lib/copy_this/www/lib/ADM.php b/lib/copy_this/newznab/controllers/ADM.php similarity index 98% rename from lib/copy_this/www/lib/ADM.php rename to lib/copy_this/newznab/controllers/ADM.php index 244fd28a9..f71b0e085 100644 --- a/lib/copy_this/www/lib/ADM.php +++ b/lib/copy_this/newznab/controllers/ADM.php @@ -1,6 +1,6 @@ <?php -require_once(WWW_DIR . "../misc/update_scripts/nix_scripts/tmux/lib/simple_html_dom.php"); +require_once NN_LIBS . 'simple_html_dom.php'; class ADM { diff --git a/lib/copy_this/www/lib/AEBN.php b/lib/copy_this/newznab/controllers/AEBN.php similarity index 98% rename from lib/copy_this/www/lib/AEBN.php rename to lib/copy_this/newznab/controllers/AEBN.php index 8988a95e2..28d1ae4f5 100644 --- a/lib/copy_this/www/lib/AEBN.php +++ b/lib/copy_this/newznab/controllers/AEBN.php @@ -1,6 +1,6 @@ <?php -require_once(WWW_DIR . "../misc/update_scripts/nix_scripts/tmux/lib/simple_html_dom.php"); +require_once NN_LIBS . 'simple_html_dom.php'; class AEBN { diff --git a/lib/copy_this/www/lib/Books.php b/lib/copy_this/newznab/controllers/Books.php similarity index 98% rename from lib/copy_this/www/lib/Books.php rename to lib/copy_this/newznab/controllers/Books.php index eb12e46bc..9d50366cf 100644 --- a/lib/copy_this/www/lib/Books.php +++ b/lib/copy_this/newznab/controllers/Books.php @@ -1,10 +1,6 @@ <?php -require_once(WWW_DIR."/lib/framework/db.php"); -require_once(WWW_DIR."/lib/amazon.php"); -require_once(WWW_DIR."/lib/category.php"); -require_once(WWW_DIR."/lib/site.php"); -require_once(WWW_DIR."/lib/util.php"); -require_once(WWW_DIR."/lib/releaseimage.php"); + +use newznab\db\DB; /* * Class for processing book info. @@ -12,7 +8,7 @@ require_once(WWW_DIR."/lib/releaseimage.php"); class Books { /** - * @var DB + * @var newznab\db\DB */ public $pdo; diff --git a/lib/copy_this/www/lib/Categorize.php b/lib/copy_this/newznab/controllers/Categorize.php similarity index 99% rename from lib/copy_this/www/lib/Categorize.php rename to lib/copy_this/newznab/controllers/Categorize.php index ee9455b8e..ad43c3aa0 100644 --- a/lib/copy_this/www/lib/Categorize.php +++ b/lib/copy_this/newznab/controllers/Categorize.php @@ -1,7 +1,4 @@ <?php -require_once(WWW_DIR . "/lib/category.php"); -require_once(WWW_DIR . "/lib/site.php"); -require_once(WWW_DIR . "/lib/Regexes.php"); /** * Categorizing of releases by name/group. @@ -53,7 +50,7 @@ class Categorize extends Category //parent::__construct($options); $s = new Sites(); $this->site = $s->get(); - $this->pdo = new DB(); + $this->pdo = new newznab\db\DB(); $this->categorizeForeign = ($this->site->categorizeforeign == "0") ? false : true; $this->catWebDL = ($this->site->catwebdl == "0") ? false : true; $this->regexes = new Regexes(['Settings' => $this->pdo, 'Table_Name' => 'category_regexes']); diff --git a/lib/copy_this/www/lib/CollectionsCleaning.php b/lib/copy_this/newznab/controllers/CollectionsCleaning.php similarity index 97% rename from lib/copy_this/www/lib/CollectionsCleaning.php rename to lib/copy_this/newznab/controllers/CollectionsCleaning.php index 02a57e143..ea1d2b384 100644 --- a/lib/copy_this/www/lib/CollectionsCleaning.php +++ b/lib/copy_this/newznab/controllers/CollectionsCleaning.php @@ -1,5 +1,4 @@ <?php -require_once(WWW_DIR . "/lib/Regexes.php"); /** * Cleans names for collections/imports/namefixer. @@ -56,7 +55,7 @@ class CollectionsCleaning public $subject = ''; /** - * @var \DB + * @var \newznab\db\DB */ public $pdo; @@ -80,7 +79,7 @@ class CollectionsCleaning ]; $options += $defaults; - $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); + $this->pdo = ($options['Settings'] instanceof newznab\db\DB ? $options['Settings'] : new newznab\db\DB()); $this->_regexes = new Regexes(['Settings' => $this->pdo, 'Table_Name' => 'collection_regexes']); } diff --git a/lib/copy_this/www/lib/ColorCLI.php b/lib/copy_this/newznab/controllers/ColorCLI.php similarity index 100% rename from lib/copy_this/www/lib/ColorCLI.php rename to lib/copy_this/newznab/controllers/ColorCLI.php diff --git a/lib/copy_this/www/lib/ConsoleTools.php b/lib/copy_this/newznab/controllers/ConsoleTools.php similarity index 99% rename from lib/copy_this/www/lib/ConsoleTools.php rename to lib/copy_this/newznab/controllers/ConsoleTools.php index 859120767..27c7515eb 100644 --- a/lib/copy_this/www/lib/ConsoleTools.php +++ b/lib/copy_this/newznab/controllers/ConsoleTools.php @@ -1,5 +1,4 @@ <?php -require_once("ColorCLI.php"); /** * Class ConsoleTools diff --git a/lib/copy_this/www/lib/Desura.php b/lib/copy_this/newznab/controllers/Desura.php similarity index 97% rename from lib/copy_this/www/lib/Desura.php rename to lib/copy_this/newznab/controllers/Desura.php index 69a5ef8fe..10803a6fb 100644 --- a/lib/copy_this/www/lib/Desura.php +++ b/lib/copy_this/newznab/controllers/Desura.php @@ -1,7 +1,8 @@ <?php -require_once(WWW_DIR . "../misc/update_scripts/nix_scripts/tmux/lib/simple_html_dom.php"); -require_once(WWW_DIR."/lib/util.php"); +require_once NN_LIBS . 'simple_html_dom.php'; + +use newznab\utility\Utility; class Desura { diff --git a/lib/copy_this/www/lib/Enzebe.php b/lib/copy_this/newznab/controllers/Enzebe.php similarity index 97% rename from lib/copy_this/www/lib/Enzebe.php rename to lib/copy_this/newznab/controllers/Enzebe.php index 6ad70559e..69ad6bca7 100644 --- a/lib/copy_this/www/lib/Enzebe.php +++ b/lib/copy_this/newznab/controllers/Enzebe.php @@ -1,7 +1,6 @@ <?php -require_once(WWW_DIR . "/lib/framework/db.php"); -require_once(WWW_DIR . "/lib/site.php"); -require_once(WWW_DIR . "/lib/category.php"); + +use newznab\db\DB; /** * Class for reading and writing NZB files on the hard disk, @@ -37,7 +36,7 @@ class Enzebe /** * Instance of class db. - * @var \DB + * @var \newznab\db\DB * @access public */ public $pdo; @@ -82,7 +81,7 @@ class Enzebe */ public function __construct(&$pdo = null) { - $this->pdo = ($pdo instanceof \DB ? $pdo : new \DB()); + $this->pdo = ($pdo instanceof DB ? $pdo : new DB()); $s = new Sites(); $this->site = $s->get(); diff --git a/lib/Film.php b/lib/copy_this/newznab/controllers/Film.php similarity index 98% rename from lib/Film.php rename to lib/copy_this/newznab/controllers/Film.php index 3dca982fa..88326ec5a 100644 --- a/lib/Film.php +++ b/lib/copy_this/newznab/controllers/Film.php @@ -1,16 +1,9 @@ <?php -require_once(dirname(__FILE__)."/../bin/config.php"); -require_once(WWW_DIR."/lib/framework/db.php"); -require_once(WWW_DIR."/lib/TMDb.php"); -require_once(WWW_DIR."/lib/site.php"); -require_once(WWW_DIR."/lib/util.php"); -require_once(WWW_DIR."/lib/category.php"); -require_once(WWW_DIR."/lib/releaseimage.php"); -require_once(WWW_DIR."/lib/rottentomato.php"); -require_once(WWW_DIR."/lib/Logger.php"); -require_once(WWW_DIR."/lib/Tmux.php"); -require_once(WWW_DIR . "/lib/ColorCLI.php"); -require_once("TraktTv.php"); +require_once NN_LIBS . 'TMDb.php'; + +use newznab\db\DB; +use newznab\utility\Utility; + /** * Class Film @@ -171,7 +164,6 @@ class Film $this->echooutput = ($options['Echo'] && NN_ECHOCLI && $this->pdo->cli); $this->imgSavePath = NN_COVERS . 'movies' . DS; $this->service = ''; - $this->utility = new Utility(); if (NN_DEBUG || NN_LOGGING) { $this->debug = true; diff --git a/lib/copy_this/www/lib/Games.php b/lib/copy_this/newznab/controllers/Games.php similarity index 97% rename from lib/copy_this/www/lib/Games.php rename to lib/copy_this/newznab/controllers/Games.php index 789783fbb..1f0cd2425 100644 --- a/lib/copy_this/www/lib/Games.php +++ b/lib/copy_this/newznab/controllers/Games.php @@ -1,16 +1,7 @@ <?php -require_once(WWW_DIR . "lib/framework/db.php"); -require_once(WWW_DIR . "lib/GiantBombAPI.php"); -require_once(WWW_DIR . "lib/Tmux.php"); -require_once(WWW_DIR . "lib/GiantBombAPI.php"); -require_once(WWW_DIR . "lib/category.php"); -require_once(WWW_DIR . "lib/genres.php"); -require_once(WWW_DIR . "lib/releaseimage.php"); -require_once(WWW_DIR . "lib/Steam.php"); -require_once(WWW_DIR . "lib/Greenlight.php"); -require_once(WWW_DIR . "lib/Desura.php"); -require_once(WWW_DIR . "lib/Logger.php"); -require_once(WWW_DIR . "/lib/ColorCLI.php"); +require_once NN_LIBS . 'GiantBombAPI.php'; + +use newznab\db\DB; class Games @@ -52,7 +43,7 @@ class Games public $maxHitRequest; /** - * @var DB + * @var newznab\db\DB */ public $pdo; @@ -112,7 +103,7 @@ class Games $this->site = $s->get(); $this->echoOutput = ($options['Echo'] && NN_ECHOCLI); - $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); + $this->pdo = ($options['Settings'] instanceof newznab\db\DB ? $options['Settings'] : new newznab\db\DB()); $this->publicKey = $this->site->giantbombkey; $this->gameQty = ($this->site->maxgamesprocessed != '') ? $this->site->maxgamesprocessed : 150; diff --git a/lib/copy_this/www/lib/Greenlight.php b/lib/copy_this/newznab/controllers/Greenlight.php similarity index 98% rename from lib/copy_this/www/lib/Greenlight.php rename to lib/copy_this/newznab/controllers/Greenlight.php index 2fa60f1d7..1552cfdc5 100644 --- a/lib/copy_this/www/lib/Greenlight.php +++ b/lib/copy_this/newznab/controllers/Greenlight.php @@ -1,7 +1,7 @@ <?php +require_once NN_LIBS . 'simple_html_dom.php'; -require_once(WWW_DIR . "../misc/update_scripts/nix_scripts/tmux/lib/simple_html_dom.php"); -require_once(WWW_DIR."/lib/util.php"); +use newznab\utility\Utility; class Greenlight { diff --git a/lib/copy_this/www/lib/Hotmovies.php b/lib/copy_this/newznab/controllers/Hotmovies.php similarity index 98% rename from lib/copy_this/www/lib/Hotmovies.php rename to lib/copy_this/newznab/controllers/Hotmovies.php index 04c98ad1e..800d17069 100644 --- a/lib/copy_this/www/lib/Hotmovies.php +++ b/lib/copy_this/newznab/controllers/Hotmovies.php @@ -1,6 +1,6 @@ <?php -require_once(WWW_DIR . "../misc/update_scripts/nix_scripts/tmux/lib/simple_html_dom.php"); +require_once NN_LIBS . 'simple_html_dom.php'; class Hotmovies { diff --git a/lib/copy_this/www/lib/IAFD.php b/lib/copy_this/newznab/controllers/IAFD.php similarity index 98% rename from lib/copy_this/www/lib/IAFD.php rename to lib/copy_this/newznab/controllers/IAFD.php index 8369b7c20..82a5d7c5e 100644 --- a/lib/copy_this/www/lib/IAFD.php +++ b/lib/copy_this/newznab/controllers/IAFD.php @@ -1,6 +1,6 @@ <?php -require_once(WWW_DIR . "../misc/update_scripts/nix_scripts/tmux/lib/simple_html_dom.php"); +require_once NN_LIBS . 'simple_html_dom.php'; class IAFD { diff --git a/lib/IRCClient.php b/lib/copy_this/newznab/controllers/IRCClient.php similarity index 100% rename from lib/IRCClient.php rename to lib/copy_this/newznab/controllers/IRCClient.php diff --git a/lib/IRCScraper.php b/lib/copy_this/newznab/controllers/IRCScraper.php similarity index 98% rename from lib/IRCScraper.php rename to lib/copy_this/newznab/controllers/IRCScraper.php index abbe7dac1..5d1cc55a6 100644 --- a/lib/IRCScraper.php +++ b/lib/copy_this/newznab/controllers/IRCScraper.php @@ -1,8 +1,6 @@ <?php -require_once(dirname(__FILE__) . "/../bin/config.php"); -require_once(WWW_DIR . "/lib/framework/db.php"); -require_once("prehash.php"); -require_once("IRCClient.php"); + +use newznab\db\DB; /** * Class IRCScraper @@ -50,7 +48,7 @@ class IRCScraper extends IRCClient protected $_oldPre; /** - * @var DB + * @var newznab\db\DB * @access protected */ protected $_pdo; diff --git a/lib/Info.php b/lib/copy_this/newznab/controllers/Info.php similarity index 95% rename from lib/Info.php rename to lib/copy_this/newznab/controllers/Info.php index 01e1259bf..a4456ad08 100644 --- a/lib/Info.php +++ b/lib/copy_this/newznab/controllers/Info.php @@ -1,16 +1,11 @@ <?php -require_once(WWW_DIR . "/lib/framework/db.php"); -require_once(WWW_DIR . "/lib/site.php"); -require_once(WWW_DIR . "/lib/Tmux.php"); -require_once(WWW_DIR . "/lib/nzb.php"); -require_once(WWW_DIR . "/lib/util.php"); -require_once(WWW_DIR . "/lib/rarinfo/par2info.php"); -require_once(WWW_DIR . "/lib/rarinfo/sfvinfo.php"); -require_once(WWW_DIR . "/lib/ColorCLI.php"); -require_once("Pprocess.php"); -require_once("Film.php"); -require_once("TvAnger.php"); -require_once("getid3/getid3/getid3.php"); +use newznab\db\DB; +use \newznab\processing\PProcess; +use newznab\utility\Utility; + +require_once NN_LIBS . 'getid3/getid3/getid3.php'; +require_once NN_LIBS . 'rarinfo/par2info.php'; +require_once NN_LIBS . 'rarinfo/sfvinfo.php'; /** * Class Nfo @@ -20,7 +15,7 @@ class Info { /** * Instance of class DB - * @var Settings + * @var newznab\db\DB * @access private */ public $pdo; diff --git a/lib/Konsole.php b/lib/copy_this/newznab/controllers/Konsole.php similarity index 98% rename from lib/Konsole.php rename to lib/copy_this/newznab/controllers/Konsole.php index a41b73bea..2e987ddbf 100644 --- a/lib/Konsole.php +++ b/lib/copy_this/newznab/controllers/Konsole.php @@ -1,13 +1,8 @@ <?php -require_once(WWW_DIR."/lib/framework/db.php"); -require_once(WWW_DIR."/lib/amazon.php"); -require_once(WWW_DIR."lib/site.php"); -require_once(WWW_DIR."/lib/category.php"); -require_once(WWW_DIR."/lib/genres.php"); -require_once(WWW_DIR."/lib/releaseimage.php"); -require_once(WWW_DIR."lib/Tmux.php"); -require_once(WWW_DIR . "/lib/ColorCLI.php"); -require_once(WWW_DIR."/lib/nzb.php"); +require_once NN_LIBS . 'AmazonProductAPI.php'; + +use newznab\db\DB; +use newznab\utility\Utility; class Konsole @@ -16,7 +11,7 @@ class Konsole const CONS_NTFND = -2; /** - * @var DB + * @var newznab\db\DB */ public $pdo; @@ -72,7 +67,7 @@ class Konsole $options += $defaults; $this->echooutput = ($options['Echo'] && NN_ECHOCLI); - $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); + $this->pdo = ($options['Settings'] instanceof newznab\db\DB ? $options['Settings'] : new newznab\db\DB()); $s = new Sites(); $this->site = $s->get(); diff --git a/lib/copy_this/www/lib/Logger.php b/lib/copy_this/newznab/controllers/Logger.php similarity index 100% rename from lib/copy_this/www/lib/Logger.php rename to lib/copy_this/newznab/controllers/Logger.php diff --git a/lib/MiscSorter.php b/lib/copy_this/newznab/controllers/MiscSorter.php similarity index 96% rename from lib/MiscSorter.php rename to lib/copy_this/newznab/controllers/MiscSorter.php index 9c7d8e48e..1b3e3fdc2 100644 --- a/lib/MiscSorter.php +++ b/lib/copy_this/newznab/controllers/MiscSorter.php @@ -1,19 +1,7 @@ <?php -require_once(WWW_DIR . "/lib/framework/db.php"); -require_once(WWW_DIR . "/lib/amazon.php"); -require_once(WWW_DIR . "/lib/Categorize.php"); -require_once(WWW_DIR . "/lib/book.php"); -require_once(WWW_DIR . "/lib/groups.php"); -require_once(WWW_DIR . "/lib/music.php"); -require_once(WWW_DIR . "/lib/Musik.php"); -require_once(WWW_DIR . "/lib/site.php"); -require_once(WWW_DIR . "/lib/nzb.php"); -require_once(WWW_DIR . "/lib/ColorCLI.php"); -require_once("Info.php"); -require_once("Film.php"); -require_once("namefixer.php"); -require_once("Konsole.php"); -require_once(WWW_DIR . "/lib/ReleaseCleaning.php"); +require_once NN_LIBS . 'AmazonProductAPI.php'; + +use newznab\db\DB; /** @@ -58,7 +46,7 @@ class MiscSorter public function nfosorter($category = 0, $id = 0) { $idarr = ($id != 0 ? sprintf('AND r.id = %d', $id) : ''); - $cat = ($category = 0 ? sprintf('AND r.categoryid = %d', Category::CAT_MISC) : sprintf('AND r.categoryid = %d', $category)); + $cat = ($category = 0 ? sprintf('AND r.categoryid = %d', Category::CAT_MISC_OTHER) : sprintf('AND r.categoryid = %d', $category)); $res = $this->pdo->queryDirect( sprintf(" diff --git a/lib/copy_this/www/lib/Musik.php b/lib/copy_this/newznab/controllers/Musik.php similarity index 99% rename from lib/copy_this/www/lib/Musik.php rename to lib/copy_this/newznab/controllers/Musik.php index ad6c515fe..956442c44 100644 --- a/lib/copy_this/www/lib/Musik.php +++ b/lib/copy_this/newznab/controllers/Musik.php @@ -1,9 +1,7 @@ <?php -require_once NN_LIB . 'amazon.php'; -require_once NN_LIB . 'util.php'; -require_once NN_LIB . 'category.php'; -require_once NN_LIB . 'releaseimage.php'; -require_once NN_LIB . 'framework' . DS . 'db.php'; +require_once NN_LIBS . 'AmazonProductAPI.php'; + +use newznab\db\DB; @@ -13,7 +11,7 @@ require_once NN_LIB . 'framework' . DS . 'db.php'; class Musik { /** - * @var DB + * @var newznab\db\DB */ public $pdo; diff --git a/lib/copy_this/newznab/controllers/NZBExport.php b/lib/copy_this/newznab/controllers/NZBExport.php new file mode 100644 index 000000000..2f0517557 --- /dev/null +++ b/lib/copy_this/newznab/controllers/NZBExport.php @@ -0,0 +1,274 @@ +<?php + +use newznab\db\DB; +use newznab\utility\Utility; + +/** + * Export NZB's to a folder. + * Class NZBExport + */ +class NZBExport +{ + /** + * Started from browser? + * @var bool + * @access protected + */ + protected $browser; + + /** + * @var string Return value on browser. + * @access protected + */ + protected $retVal; + + /** + * @var \newznab\db\DB + * @access protected + */ + protected $pdo; + + /** + * @var NZB + * @access protected + */ + protected $nzb; + + /** + * @var Releases + * @access protected + */ + protected $releases; + + /** + * @var bool + * @access protected + */ + protected $echoCLI; + + /** + * @param array $options Class instances / various options. + * + * @access public + */ + public function __construct(array $options = array()) + { + $defaults = [ + 'Browser' => false, // Started from browser? + 'Echo' => true, // Echo to CLI? + 'NZB' => null, + 'Releases' => null, + 'Settings' => null, + ]; + $options += $defaults; + + $this->browser = $options['Browser']; + $this->echoCLI = (!$this->browser && NN_ECHOCLI && $options['Echo']); + $this->pdo = ($options['Settings'] instanceof DB ? $options['Setting'] : new DB()); + $this->releases = ($options['Releases'] instanceof \Releases ? $options['Releases'] : new \Releases(['Settings' => $this->pdo])); + $this->nzb = ($options['NZB'] instanceof \NZB ? $options['NZB'] : new \NZB($this->pdo)); + } + + /** + * Export to user specified folder. + * + * @param array $params + * + * @return bool + * + * @access public + */ + public function beginExport($params) + { + $gzip = false; + if ($params[4] === true) { + $gzip = true; + } + + $fromDate = $toDate = ''; + $path = $params[0]; + + // Check if the path ends with dir separator. + if (substr($path, -1) !== DS) { + $path .= DS; + } + + // Check if it's a directory. + if (!is_dir($path)) { + $this->echoOut('Folder does not exist: ' . $path); + return $this->returnValue(); + } + + // Check if we can write to it. + if (!is_writable($path)) { + $this->echoOut('Folder is not writable: ' . $path); + return $this->returnValue(); + } + + // Check if the from date is the proper format. + if (isset($params[1]) && $params[1] !== '') { + if (!$this->checkDate($params[1])) { + return $this->returnValue(); + } + $fromDate = $params[1]; + } + + // Check if the to date is the proper format. + if (isset($params[2]) && $params[2] !== '') { + if (!$this->checkDate($params[2])) { + return $this->returnValue(); + } + $toDate = $params[2]; + } + + // Check if the group_id exists. + if (isset($params[3]) && $params[3] !== 0) { + if (!is_numeric($params[3])) { + $this->echoOut('The group ID is not a number: ' . $params[3]); + return $this->returnValue(); + } + $groups = $this->pdo->query('SELECT id, name FROM groups WHERE id = ' . $params[3]); + if (count($groups) === 0) { + $this->echoOut('The group ID is not in the DB: ' . $params[3]); + return $this->returnValue(); + } + } else { + $groups = $this->pdo->query('SELECT id, name FROM groups'); + } + + $exported = 0; + // Loop over groups to take less RAM. + foreach ($groups as $group) { + $currentExport = 0; + // Get all the releases based on the parameters. + $releases = $this->releases->getForExport($fromDate, $toDate, $group['id']); + $totalFound = count($releases); + if ($totalFound === 0) { + if ($this->echoCLI) { + echo 'No releases found to export for group: ' . $group['name'] . PHP_EOL; + } + continue; + } + if ($this->echoCLI) { + echo 'Found ' . $totalFound . ' releases to export for group: ' . $group['name'] . PHP_EOL; + } + + // Create a path to store the new NZB files. + $currentPath = $path . $this->safeFilename($group['name']) . DS; + if (!is_dir($currentPath)) { + mkdir($currentPath); + } + foreach ($releases as $release) { + + // Get path to the NZB file. + $nzbFile = $this->nzb->NZBPath($release["guid"]); + // Check if it exists. + if ($nzbFile === false) { + if ($this->echoCLI) { + echo 'Unable to find NZB for release with GUID: ' . $release['guid']; + } + continue; + } + + // Create path to current file. + $currentFile = $currentPath . $this->safeFilename($release['searchname']); + + // Check if the user wants them in gzip, copy it if so. + if ($gzip) { + if (!copy($nzbFile, $currentFile . '.nzb.gz')) { + if ($this->echoCLI) { + echo 'Unable to export NZB with GUID: ' . $release['guid']; + } + continue; + } + // If not, decompress it and create a file to store it in. + } else { + $nzbContents = Utility::unzipGzipFile($nzbFile); + if (!$nzbContents) { + if ($this->echoCLI) { + echo 'Unable to export NZB with GUID: ' . $release['guid']; + } + continue; + } + $fh = fopen($currentFile . '.nzb', 'w'); + fwrite($fh, $nzbContents); + fclose($fh); + } + + $currentExport++; + + if ($this->echoCLI && $currentExport % 10 === 0) { + echo 'Exported ' . $currentExport . ' of ' . $totalFound . ' nzbs for group: ' . $group['name'] . "\r"; + } + } + if ($this->echoCLI && $currentExport > 0) { + echo 'Exported ' . $currentExport . ' of ' . $totalFound . ' nzbs for group: ' . $group['name'] . PHP_EOL; + } + $exported += $currentExport; + } + if ($exported > 0) { + $this->echoOut('Exported total of ' . $exported . ' NZB files to ' . $path); + } + + return $this->returnValue(); + } + + /** + * Return bool on CLI, string on browser. + * @return bool|string + * + * @access protected + */ + protected function returnValue() + { + return ($this->browser ? $this->retVal : true); + } + + /** + * Check if date is in good format. + * + * @param string $date + * + * @return bool + * + * @access protected + */ + protected function checkDate($date) + { + if (!preg_match('/^(\d{2}\/){2}\d{4}$/', $date)) { + $this->echoOut('Wrong date format: ' . $date); + return false; + } + return true; + } + + /** + * Echo message to browser or CLI. + * + * @param string $message + * + * @access protected + */ + protected function echoOut($message) + { + if ($this->browser) { + $this->retVal .= $message . "<br />"; + } elseif ($this->echoCLI) { + echo $message . PHP_EOL; + } + } + + /** + * Remove unsafe chars from a filename. + * + * @param string $filename + * + * @return string + * + * @access protected + */ + protected function safeFilename($filename) + { + return trim(preg_replace('/[^\w\s.-]*/i', '', $filename)); + } +} \ No newline at end of file diff --git a/lib/NZBGet.php b/lib/copy_this/newznab/controllers/NZBGet.php similarity index 97% rename from lib/NZBGet.php rename to lib/copy_this/newznab/controllers/NZBGet.php index 3b0616702..f04bddf1a 100644 --- a/lib/NZBGet.php +++ b/lib/copy_this/newznab/controllers/NZBGet.php @@ -1,14 +1,13 @@ <?php -require_once(dirname(__FILE__) . "/../bin/config.php"); -require_once(WWW_DIR . "/lib/releases.php"); -require_once(WWW_DIR . "/lib/util.php"); -require_once(WWW_DIR . "/lib/nzb.php"); + +use newznab\utility\Utility; + /** * Class NZBGet * * Transfers data between an NZBGet server and a newznab website. * - * @package nzedb + * @package newznab */ class NZBGet { diff --git a/lib/copy_this/www/lib/NZBImport.php b/lib/copy_this/newznab/controllers/NZBImport.php similarity index 96% rename from lib/copy_this/www/lib/NZBImport.php rename to lib/copy_this/newznab/controllers/NZBImport.php index db3f71ccc..257a2f159 100644 --- a/lib/copy_this/www/lib/NZBImport.php +++ b/lib/copy_this/newznab/controllers/NZBImport.php @@ -1,12 +1,7 @@ <?php -require_once(WWW_DIR . "/lib/framework/db.php"); -require_once(WWW_DIR . "/lib/binaries.php"); -require_once(WWW_DIR . "/lib/releases.php"); -require_once(WWW_DIR . "/lib/nzb.php"); -require_once(WWW_DIR . "/lib/site.php"); -require_once(WWW_DIR . "/lib/util.php"); -require_once(WWW_DIR . "/lib/Categorize.php"); -require_once(WWW_DIR . "/lib/ReleaseCleaning.php"); + +use newznab\db\DB; +use newznab\utility\Utility; /** * Import NZB files into the database. @@ -15,7 +10,7 @@ require_once(WWW_DIR . "/lib/ReleaseCleaning.php"); class NZBImport { /** - * @var \DB + * @var \newznab\db\DB * @access protected */ protected $pdo; diff --git a/lib/copy_this/www/lib/Popporn.php b/lib/copy_this/newznab/controllers/Popporn.php similarity index 99% rename from lib/copy_this/www/lib/Popporn.php rename to lib/copy_this/newznab/controllers/Popporn.php index 7d3c5007b..ba9aee2a7 100644 --- a/lib/copy_this/www/lib/Popporn.php +++ b/lib/copy_this/newznab/controllers/Popporn.php @@ -1,6 +1,6 @@ <?php -require_once(WWW_DIR . "../misc/update_scripts/nix_scripts/tmux/lib/simple_html_dom.php"); +require_once NN_LIBS . 'simple_html_dom.php'; class Popporn { diff --git a/lib/copy_this/www/lib/Regexes.php b/lib/copy_this/newznab/controllers/Regexes.php similarity index 98% rename from lib/copy_this/www/lib/Regexes.php rename to lib/copy_this/newznab/controllers/Regexes.php index e7a9ee665..8b35cea92 100644 --- a/lib/copy_this/www/lib/Regexes.php +++ b/lib/copy_this/newznab/controllers/Regexes.php @@ -1,12 +1,11 @@ <?php -require_once(WWW_DIR . "/lib/groups.php"); -require_once(WWW_DIR . "/lib/framework/db.php"); -require_once(WWW_DIR . "/lib/category.php"); + +use newznab\db\DB; Class Regexes { /** - * @var \DB + * @var \newznab\db\DB */ public $pdo; diff --git a/lib/copy_this/www/lib/ReleaseCleaning.php b/lib/copy_this/newznab/controllers/ReleaseCleaning.php similarity index 98% rename from lib/copy_this/www/lib/ReleaseCleaning.php rename to lib/copy_this/newznab/controllers/ReleaseCleaning.php index 1d920898c..9f04ae05c 100644 --- a/lib/copy_this/www/lib/ReleaseCleaning.php +++ b/lib/copy_this/newznab/controllers/ReleaseCleaning.php @@ -1,9 +1,7 @@ <?php -require_once(WWW_DIR . "lib/framework/db.php"); -require_once(WWW_DIR . "lib/groups.php"); -require_once(WWW_DIR . "lib/CollectionsCleaning.php"); -require_once(WWW_DIR . "lib/Regexes.php"); -require_once(NN_TMUX . 'lib' . DS . 'prehash.php'); + +use newznab\db\DB; + /* * Cleans names for releases/imports/namefixer. * Names of group functions should match between CollectionsCleaning and this file @@ -59,7 +57,7 @@ class ReleaseCleaning public $groupName = ''; /** - * @var DB + * @var newznab\db\DB */ public $pdo; @@ -88,7 +86,7 @@ class ReleaseCleaning $this->e1 = \CollectionsCleaning::REGEX_FILE_EXTENSIONS . \CollectionsCleaning::REGEX_END; $this->e2 = \CollectionsCleaning::REGEX_FILE_EXTENSIONS . \CollectionsCleaning::REGEX_SUBJECT_SIZE . \CollectionsCleaning::REGEX_END; - $this->pdo = ($settings instanceof DB ? $settings : new DB()); + $this->pdo = ($settings instanceof newznab\db\DB ? $settings : new newznab\db\DB()); $this->_regexes = new Regexes(['Settings' => $this->pdo, 'Table_Name' => 'release_naming_regexes']); } diff --git a/lib/ReleaseRemover.php b/lib/copy_this/newznab/controllers/ReleaseRemover.php similarity index 98% rename from lib/ReleaseRemover.php rename to lib/copy_this/newznab/controllers/ReleaseRemover.php index ac6f789c2..53d311222 100644 --- a/lib/ReleaseRemover.php +++ b/lib/copy_this/newznab/controllers/ReleaseRemover.php @@ -1,13 +1,6 @@ <?php -require_once(WWW_DIR . "/lib/framework/cache.php"); -require_once(WWW_DIR . "/lib/framework/db.php"); -require_once(WWW_DIR . "/lib/releases.php"); -require_once(WWW_DIR . "/lib/category.php"); -require_once(WWW_DIR . "/lib/binaries.php"); -require_once(WWW_DIR . "/lib/releaseimage.php"); -require_once(WWW_DIR . "/lib/ConsoleTools.php"); -require_once(WWW_DIR . "/lib/ColorCLI.php"); -require_once(WWW_DIR . "/lib/nzb.php"); + +use newznab\db\DB; /** @@ -79,7 +72,7 @@ class ReleaseRemover protected $method = ''; /** - * @var DB + * @var newznab\db\DB */ protected $pdo; diff --git a/lib/copy_this/www/lib/ReleaseSearch.php b/lib/copy_this/newznab/controllers/ReleaseSearch.php similarity index 97% rename from lib/copy_this/www/lib/ReleaseSearch.php rename to lib/copy_this/newznab/controllers/ReleaseSearch.php index 2a79cf7cf..681819e16 100644 --- a/lib/copy_this/www/lib/ReleaseSearch.php +++ b/lib/copy_this/newznab/controllers/ReleaseSearch.php @@ -1,5 +1,7 @@ <?php -require_once(WWW_DIR . "lib/framework/db.php"); + +use newznab\db\DB; + class ReleaseSearch { const FULLTEXT = 0; @@ -7,7 +9,7 @@ class ReleaseSearch const SPHINX = 2; /*** - * @var DB + * @var newznab\db\DB */ public $pdo; @@ -41,7 +43,7 @@ class ReleaseSearch break; } - $this->pdo = ($settings instanceof DB ? $settings : new DB()); + $this->pdo = ($settings instanceof newznab\db\DB ? $settings : new newznab\db\DB()); } /** diff --git a/lib/copy_this/www/lib/RequestID.php b/lib/copy_this/newznab/controllers/RequestID.php similarity index 95% rename from lib/copy_this/www/lib/RequestID.php rename to lib/copy_this/newznab/controllers/RequestID.php index 2ae04a8c0..7e3e5602c 100644 --- a/lib/copy_this/www/lib/RequestID.php +++ b/lib/copy_this/newznab/controllers/RequestID.php @@ -1,9 +1,6 @@ <?php -require_once (NN_LIB . 'framework' . DS . 'db.php'); -require_once (NN_LIB . 'Categorize.php'); -require_once (NN_LIB . 'groups.php'); -require_once (NN_LIB . 'ConsoleTools.php'); -require_once (NN_LIB . 'SphinxSearch.php'); + +use newznab\db\DB; abstract class RequestID { @@ -159,7 +156,7 @@ abstract class RequestID protected $category; /** - * @var DB + * @var newznab\db\DB */ protected $pdo; diff --git a/lib/copy_this/www/lib/RequestIDLocal.php b/lib/copy_this/newznab/controllers/RequestIDLocal.php similarity index 99% rename from lib/copy_this/www/lib/RequestIDLocal.php rename to lib/copy_this/newznab/controllers/RequestIDLocal.php index 410c06fdb..555bd6098 100644 --- a/lib/copy_this/www/lib/RequestIDLocal.php +++ b/lib/copy_this/newznab/controllers/RequestIDLocal.php @@ -1,5 +1,4 @@ <?php -require_once (NN_LIB . 'RequestID.php'); /** * Attempts to find a PRE name for a release using a request id from our local pre database, diff --git a/lib/copy_this/www/lib/RequestIDWeb.php b/lib/copy_this/newznab/controllers/RequestIDWeb.php similarity index 99% rename from lib/copy_this/www/lib/RequestIDWeb.php rename to lib/copy_this/newznab/controllers/RequestIDWeb.php index 32da3832b..78487f5ee 100644 --- a/lib/copy_this/www/lib/RequestIDWeb.php +++ b/lib/copy_this/newznab/controllers/RequestIDWeb.php @@ -1,7 +1,6 @@ <?php -require_once (NN_LIB . 'util.php'); -require_once (NN_LIB . 'RequestID.php'); +use newznab\utility\Utility; /** * Attempts to find a PRE name for a release using a request id from our local pre database, diff --git a/lib/Sharing.php b/lib/copy_this/newznab/controllers/Sharing.php similarity index 99% rename from lib/Sharing.php rename to lib/copy_this/newznab/controllers/Sharing.php index d893acfb8..a63dc460a 100644 --- a/lib/Sharing.php +++ b/lib/copy_this/newznab/controllers/Sharing.php @@ -1,6 +1,7 @@ <?php -require_once(WWW_DIR . "lib/framework/db.php"); -require_once(WWW_DIR . '/lib/nntp.php'); + +use newznab\db\DB; + /** * @@ -44,9 +45,9 @@ Class Sharing */ /** - * @var DB + * @var \newznab\db\DB */ - protected $db; + protected $pdo; /** * @var NNTP diff --git a/lib/copy_this/www/lib/sitemaps.php b/lib/copy_this/newznab/controllers/Sitemap.php similarity index 100% rename from lib/copy_this/www/lib/sitemaps.php rename to lib/copy_this/newznab/controllers/Sitemap.php diff --git a/lib/copy_this/www/lib/SphinxSearch.php b/lib/copy_this/newznab/controllers/SphinxSearch.php similarity index 96% rename from lib/copy_this/www/lib/SphinxSearch.php rename to lib/copy_this/newznab/controllers/SphinxSearch.php index 8a89bd5b1..4a47e628d 100644 --- a/lib/copy_this/www/lib/SphinxSearch.php +++ b/lib/copy_this/newznab/controllers/SphinxSearch.php @@ -1,12 +1,11 @@ <?php -require_once (NN_LIB . 'ReleaseSearch.php'); -require_once (NN_LIB . 'framework' . DS . 'db.php'); +use newznab\db\DB; class SphinxSearch { /** * SphinxQL connection. - * @var DB + * @var newznab\db\DB */ public $sphinxQL = null; @@ -25,7 +24,7 @@ class SphinxSearch if (!defined('NN_SPHINXQL_SOCK_FILE')) { define('NN_SPHINXQL_SOCK_FILE', ''); } - $this->sphinxQL = new DB( + $this->sphinxQL = new newznab\db\DB( [ 'dbname' => '', 'dbport' => NN_SPHINXQL_PORT, diff --git a/lib/copy_this/www/lib/Steam.php b/lib/copy_this/newznab/controllers/Steam.php similarity index 98% rename from lib/copy_this/www/lib/Steam.php rename to lib/copy_this/newznab/controllers/Steam.php index 32d541c80..ba72bae16 100644 --- a/lib/copy_this/www/lib/Steam.php +++ b/lib/copy_this/newznab/controllers/Steam.php @@ -1,7 +1,7 @@ <?php +require_once NN_LIBS . 'simple_html_dom.php'; -require_once(WWW_DIR . "../misc/update_scripts/nix_scripts/tmux/lib/simple_html_dom.php"); -require_once(WWW_DIR . "lib/util.php"); +use newznab\utility\Utility; class Steam { diff --git a/lib/copy_this/www/lib/Tmux.php b/lib/copy_this/newznab/controllers/Tmux.php similarity index 98% rename from lib/copy_this/www/lib/Tmux.php rename to lib/copy_this/newznab/controllers/Tmux.php index dd5312146..76224ff6a 100644 --- a/lib/copy_this/www/lib/Tmux.php +++ b/lib/copy_this/newznab/controllers/Tmux.php @@ -1,13 +1,12 @@ <?php -require_once (NN_LIB . 'framework' . DS . 'db.php'); -require_once (NN_LIB . 'site.php'); -require_once (NN_TMUX . 'lib' . DS . 'Info.php'); + +use newznab\db\DB; class Tmux { /** - * @var \DB + * @var \newznab\db\DB */ public $pdo; @@ -15,7 +14,7 @@ class Tmux function __construct(DB $pdo = null) { - $this->pdo = (empty($pdo) ? new DB() : $pdo); + $this->pdo = (empty($pdo) ? new newznab\db\DB() : $pdo); $s = new Sites; $this->site = $s->get(); } diff --git a/lib/copy_this/www/lib/TmuxOutput.php b/lib/copy_this/newznab/controllers/TmuxOutput.php similarity index 99% rename from lib/copy_this/www/lib/TmuxOutput.php rename to lib/copy_this/newznab/controllers/TmuxOutput.php index cdf3e5e28..0cd83f913 100644 --- a/lib/copy_this/www/lib/TmuxOutput.php +++ b/lib/copy_this/newznab/controllers/TmuxOutput.php @@ -1,9 +1,4 @@ <?php - -require_once (NN_LIB . 'Tmux.php'); -require_once (NN_LIB . 'site.php'); - - /** * Tmux output functions for printing monitor data * @@ -25,9 +20,9 @@ class TmuxOutput extends Tmux /** - * @param DB $pdo + * @param newznab\db\DB $pdo */ - public function __construct(DB $pdo = null) + public function __construct(newznab\db\DB $pdo = null) { parent::__construct($pdo); diff --git a/lib/copy_this/www/lib/TmuxRun.php b/lib/copy_this/newznab/controllers/TmuxRun.php similarity index 99% rename from lib/copy_this/www/lib/TmuxRun.php rename to lib/copy_this/newznab/controllers/TmuxRun.php index 7fa82c042..7cf03f004 100644 --- a/lib/copy_this/www/lib/TmuxRun.php +++ b/lib/copy_this/newznab/controllers/TmuxRun.php @@ -1,7 +1,4 @@ <?php -require_once(NN_LIB . 'Tmux.php'); - - /** * Tmux pane shell exec functions for pane respawning * @@ -12,9 +9,9 @@ class TmuxRun extends Tmux protected $_dateFormat; /** - * @param DB $pdo + * @param newznab\db\DB $pdo */ - public function __construct(DB $pdo = null) + public function __construct(newznab\db\DB $pdo = null) { parent::__construct($pdo); $this->_dateFormat = '%Y-%m-%d %T'; diff --git a/lib/TraktTv.php b/lib/copy_this/newznab/controllers/TraktTv.php similarity index 94% rename from lib/TraktTv.php rename to lib/copy_this/newznab/controllers/TraktTv.php index 1b687162c..2b04ad998 100644 --- a/lib/TraktTv.php +++ b/lib/copy_this/newznab/controllers/TraktTv.php @@ -1,7 +1,6 @@ <?php -require_once(WWW_DIR . '/lib/framework/db.php'); -require_once(WWW_DIR . '/lib/Tmux.php'); -require_once(WWW_DIR . '/lib/util.php'); + +use newznab\utility\Utility; /** * Class TraktTv diff --git a/lib/TvAnger.php b/lib/copy_this/newznab/controllers/TvAnger.php similarity index 98% rename from lib/TvAnger.php rename to lib/copy_this/newznab/controllers/TvAnger.php index de66de2cd..adefa4b7a 100644 --- a/lib/TvAnger.php +++ b/lib/copy_this/newznab/controllers/TvAnger.php @@ -1,11 +1,7 @@ <?php -require_once(WWW_DIR . "/lib/framework/db.php"); -require_once(WWW_DIR . "/lib/category.php"); -require_once(WWW_DIR . "/lib/Tmux.php"); -require_once(WWW_DIR . "/lib/util.php"); -require_once(WWW_DIR . "/lib/ColorCLI.php"); -require_once(WWW_DIR . "/lib/Logger.php"); -require_once("TraktTv.php"); + +use newznab\db\DB; +use newznab\utility\Utility; /** * Class TvAnger @@ -16,7 +12,7 @@ class TvAnger const MATCH_PROBABILITY = 75; /** - * @var Settings + * @var newznab\db\DB */ public $pdo; @@ -468,7 +464,7 @@ class TvAnger } $xmlObj = @simplexml_load_string($xml); - $arrXml = objectsIntoArray($xmlObj); + $arrXml = Utility::objectsIntoArray($xmlObj); if (is_array($arrXml)) { if (isset($arrXml['episode']['airdate']) && $arrXml['episode']['airdate'] != '0000-00-00') { $result['airdate'] = $arrXml['episode']['airdate']; @@ -520,7 +516,7 @@ class TvAnger // Full search gives us the akas. $xml =Utility::getUrl(['url' => $this->xmlShowInfoUrl . $rageID]); if ($xml !== false) { - $arrXml = objectsIntoArray(simplexml_load_string($xml)); + $arrXml = Utility::objectsIntoArray(simplexml_load_string($xml)); if (is_array($arrXml)) { $result['genres'] = (isset($arrXml['genres'])) ? $arrXml['genres'] : ''; $result['country'] = (isset($arrXml['origin_country'])) ? $arrXml['origin_country'] : ''; @@ -767,7 +763,7 @@ class TvAnger // Full search gives us the akas. $xml = Utility::getUrl(['url' => $this->xmlFullSearchUrl . urlencode(strtolower($title))]); if ($xml !== false) { - $arrXml = @objectsIntoArray(simplexml_load_string($xml)); + $arrXml = @Utility::objectsIntoArray(simplexml_load_string($xml)); if (isset($arrXml['show']) && is_array($arrXml)) { // We got a valid xml response $titleMatches = $urlMatches = $akaMatches = array(); diff --git a/lib/copy_this/www/lib/XXX.php b/lib/copy_this/newznab/controllers/XXX.php similarity index 97% rename from lib/copy_this/www/lib/XXX.php rename to lib/copy_this/newznab/controllers/XXX.php index 5803aabbc..c9c44665e 100644 --- a/lib/copy_this/www/lib/XXX.php +++ b/lib/copy_this/newznab/controllers/XXX.php @@ -1,15 +1,6 @@ <?php -require_once(WWW_DIR . "/lib/framework/db.php"); -require_once(WWW_DIR . "/lib/releaseimage.php"); -require_once(WWW_DIR . "/lib/IAFD.php"); -require_once(WWW_DIR . "/lib/ADM.php"); -require_once(WWW_DIR . "/lib/ADE.php"); -require_once(WWW_DIR . "/lib/AEBN.php"); -require_once(WWW_DIR . "/lib/Hotmovies.php"); -require_once(WWW_DIR . "/lib/Popporn.php"); -require_once(WWW_DIR . "/lib/category.php"); -require_once(WWW_DIR . "/lib/ColorCLI.php"); -require_once(WWW_DIR . "/lib/Logger.php"); + +use newznab\db\DB; /** @@ -18,7 +9,7 @@ require_once(WWW_DIR . "/lib/Logger.php"); class XXX { /** - * @var DB + * @var newznab\db\DB */ public $pdo; diff --git a/lib/copy_this/www/lib/adminpage.php b/lib/copy_this/newznab/controllers/adminpage.php similarity index 89% rename from lib/copy_this/www/lib/adminpage.php rename to lib/copy_this/newznab/controllers/adminpage.php index 21af64cf0..95adf4340 100644 --- a/lib/copy_this/www/lib/adminpage.php +++ b/lib/copy_this/newznab/controllers/adminpage.php @@ -1,7 +1,5 @@ <?php -require_once("config.php"); -require_once(WWW_DIR."/lib/framework/basepage.php"); -require_once(WWW_DIR."/lib/users.php"); +require_once './config.php'; /** * All admin pages implement this class. Enforces admin role for requesting user. diff --git a/lib/copy_this/www/lib/anidb.php b/lib/copy_this/newznab/controllers/anidb.php similarity index 98% rename from lib/copy_this/www/lib/anidb.php rename to lib/copy_this/newznab/controllers/anidb.php index 78bc00af4..24cc00879 100644 --- a/lib/copy_this/www/lib/anidb.php +++ b/lib/copy_this/newznab/controllers/anidb.php @@ -1,10 +1,11 @@ <?php -require_once(WWW_DIR . "/lib/framework/db.php"); + +use newznab\db\DB; class AniDB { /** - * @var DB + * @var newznab\db\DB */ public $pdo; diff --git a/lib/copy_this/www/lib/backfill.php b/lib/copy_this/newznab/controllers/backfill.php similarity index 96% rename from lib/copy_this/www/lib/backfill.php rename to lib/copy_this/newznab/controllers/backfill.php index b7653680e..5da1a6920 100644 --- a/lib/copy_this/www/lib/backfill.php +++ b/lib/copy_this/newznab/controllers/backfill.php @@ -1,18 +1,13 @@ <?php -require_once(WWW_DIR."/lib/framework/db.php"); -require_once(WWW_DIR."/lib/groups.php"); -require_once(WWW_DIR."/lib/nntp.php"); -require_once(WWW_DIR."/lib/site.php"); -require_once(WWW_DIR."/lib/binaries.php"); -require_once(WWW_DIR."/lib/ColorCLI.php"); -require_once(WWW_DIR."/lib/Logger.php"); + +use newznab\db\DB; class Backfill { /** * Instance of class Settings * - * @var DB + * @var newznab\db\DB */ public $pdo; @@ -100,7 +95,7 @@ class Backfill $this->_echoCLI = ($options['Echo'] && NN_ECHOCLI); - $this->pdo = ($options['Settings'] instanceof \DB ? $options['Settings'] : new \DB()); + $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); $this->_groups = ($options['Groups'] instanceof \Groups ? $options['Groups'] : new \Groups(['Settings' => $this->pdo])); $this->_nntp = ($options['NNTP'] instanceof \NNTP ? $options['NNTP'] : new \NNTP(['Settings' => $this->pdo]) diff --git a/lib/copy_this/www/lib/framework/basepage.php b/lib/copy_this/newznab/controllers/basepage.php similarity index 96% rename from lib/copy_this/www/lib/framework/basepage.php rename to lib/copy_this/newznab/controllers/basepage.php index 659aa3de4..97b8ef7ea 100644 --- a/lib/copy_this/www/lib/framework/basepage.php +++ b/lib/copy_this/newznab/controllers/basepage.php @@ -1,15 +1,11 @@ <?php -require_once(SMARTY_DIR.'Smarty.class.php'); -require_once(NN_LIB .'framework' . DS . 'db.php'); -require_once(WWW_DIR."/lib/users.php"); -require_once(WWW_DIR."/lib/site.php"); -require_once(WWW_DIR."/lib/sabnzbd.php"); -require_once (NN_LIB . 'SmartyUtils.php'); +require_once SMARTY_DIR . 'Smarty.class.php'; +require_once NN_LIB . 'utility' . DS . 'SmartyUtils.php'; class BasePage { /** - * @var DB + * @var \newznab\db\DB */ public $settings = null; @@ -54,7 +50,7 @@ class BasePage $this->site = $s->get(); // Buffer settings/DB connection. - $this->settings = new DB(); + $this->settings = new newznab\db\DB(); $this->smarty = new Smarty(); if ($this->site->style != "default") diff --git a/lib/copy_this/www/lib/binaries.php b/lib/copy_this/newznab/controllers/binaries.php similarity index 98% rename from lib/copy_this/www/lib/binaries.php rename to lib/copy_this/newznab/controllers/binaries.php index 2f0501a8d..2a2e50061 100644 --- a/lib/copy_this/www/lib/binaries.php +++ b/lib/copy_this/newznab/controllers/binaries.php @@ -1,13 +1,6 @@ <?php -require_once(NN_LIB . 'framework' . DS . 'db.php'); -require_once(NN_LIB . 'nzb.php'); -require_once(NN_LIB . 'groups.php'); -require_once(NN_LIB . 'ConsoleTools.php'); -require_once(NN_LIB . 'CollectionsCleaning.php'); -require_once(NN_LIB . 'ColorCLI.php'); -require_once(NN_LIB . 'nntp.php'); -require_once(NN_LIB . 'site.php'); -require_once(NN_LIB . 'Logger.php'); + +use newznab\db\DB; /** * Class Binaries @@ -84,7 +77,7 @@ class Binaries protected $_partRepair; /** - * @var DB + * @var newznab\db\DB */ protected $_pdo; @@ -170,7 +163,7 @@ class Binaries $s = new Sites(); $this->_site = $s->get(); - $this->_pdo = ($options['Settings'] instanceof \DB ? $options['Settings'] : new \DB()); + $this->_pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); $this->_groups = ($options['Groups'] instanceof \Groups ? $options['Groups'] : new \Groups(['Settings' => $this->_pdo])); $this->_colorCLI = ($options['ColorCLI'] instanceof \ColorCLI ? $options['ColorCLI'] : new \ColorCLI()); $this->_nntp = ($options['NNTP'] instanceof \NNTP ? $options['NNTP'] : new \NNTP(['Echo' => $this->_colorCLI, 'Settings' => $this->_pdo, 'ColorCLI' => $this->_colorCLI])); diff --git a/lib/copy_this/www/lib/book.php b/lib/copy_this/newznab/controllers/book.php similarity index 98% rename from lib/copy_this/www/lib/book.php rename to lib/copy_this/newznab/controllers/book.php index 4ce719927..a08b286cf 100644 --- a/lib/copy_this/www/lib/book.php +++ b/lib/copy_this/newznab/controllers/book.php @@ -1,10 +1,7 @@ <?php -require_once(WWW_DIR."/lib/framework/db.php"); -require_once(WWW_DIR."/lib/amazon.php"); -require_once(WWW_DIR."/lib/category.php"); -require_once(WWW_DIR."/lib/site.php"); -require_once(WWW_DIR."/lib/util.php"); -require_once(WWW_DIR."/lib/releaseimage.php"); + +use newznab\db\DB; + /** * This class manages the lookup of book information and storage/retrieve of book metadata. @@ -14,7 +11,7 @@ class Book const NUMTOPROCESSPERTIME = 100; /** - * @var DB + * @var newznab\db\DB */ public $pdo; @@ -255,8 +252,6 @@ class Book */ public function update($id, $title, $asin, $url, $author, $publisher, $publishdate, $cover) { - $db = new DB(); - $this->pdo->queryExec(sprintf("update bookinfo SET title=%s, asin=%s, url=%s, author=%s, publisher=%s, publishdate='%s', cover=%d, updateddate=NOW() WHERE id = %d", $this->pdo->escapeString($title), $this->pdo->escapeString($asin), $this->pdo->escapeString($url), $this->pdo->escapeString($author), $this->pdo->escapeString($publisher), $publishdate, $cover, $id)); } diff --git a/lib/copy_this/www/lib/category.php b/lib/copy_this/newznab/controllers/category.php similarity index 92% rename from lib/copy_this/www/lib/category.php rename to lib/copy_this/newznab/controllers/category.php index c95ddb7e2..583a2b10d 100644 --- a/lib/copy_this/www/lib/category.php +++ b/lib/copy_this/newznab/controllers/category.php @@ -1,6 +1,6 @@ <?php -require_once(WWW_DIR . "/lib/framework/db.php"); -require_once(WWW_DIR . "lib/Categorize.php"); + +use newznab\db\DB; /** * This class manages the site wide categories. @@ -84,6 +84,26 @@ class Category private $tmpCat = 0; + /** + * @var newznab\db\DB + */ + public $pdo; + + /** + * Construct. + * + * @param array $options Class instances. + */ + public function __construct(array $options = array()) + { + $defaults = [ + 'Settings' => null, + ]; + $options += $defaults; + + $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); + } + /** * Parse category search constraints * @@ -123,7 +143,7 @@ class Category */ public function isParent($cid) { - $db = new DB(); + $db = new newznab\db\DB(); $ret = $db->queryOneRow(sprintf("select count(*) as count from category where id = %d and parentid is null", $cid), true); if ($ret['count']) return true; @@ -136,7 +156,7 @@ class Category */ public function getChildren($cid) { - $db = new DB(); + $db = new newznab\db\DB(); return $db->query(sprintf("select c.* from category c where parentid = %d", $cid), true); } @@ -146,7 +166,7 @@ class Category */ public function getFlat($activeonly = false) { - $db = new DB(); + $db = new newznab\db\DB(); $act = ""; if ($activeonly) $act = sprintf(" where c.status = %d ", Category::STATUS_ACTIVE); @@ -161,7 +181,7 @@ class Category */ public function getEnabledParentNames() { - $db = new DB(); + $db = new newznab\db\DB(); return $db->query("SELECT title FROM category WHERE parentid IS NULL AND status = 1"); } @@ -173,7 +193,7 @@ class Category */ public function getDisabledIDs() { - $db = new DB(); + $db = new newznab\db\DB(); return $db->query("SELECT id FROM category WHERE status = 2 OR parentid IN (SELECT id FROM category WHERE status = 2 AND parentid IS NULL)"); } @@ -182,14 +202,14 @@ class Category */ public function getById($id) { - $db = new DB(); + $db = new newznab\db\DB(); return $db->queryOneRow(sprintf("SELECT c.disablepreview, c.id, c.description, c.minsizetoformrelease, c.maxsizetoformrelease, CONCAT(COALESCE(cp.title,'') , CASE WHEN cp.title IS NULL THEN '' ELSE ' > ' END , c.title) as title, c.status, c.parentid from category c left outer join category cp on cp.id = c.parentid where c.id = %d", $id)); } public function getSizeRangeById($id) { - $db = new DB(); + $db = new newznab\db\DB(); $res = $db->queryOneRow(sprintf("SELECT c.minsizetoformrelease, c.maxsizetoformrelease, cp.minsizetoformrelease as p_minsizetoformrelease, cp.maxsizetoformrelease as p_maxsizetoformrelease" . " from category c left outer join category cp on cp.id = c.parentid where c.id = %d", $id ) @@ -235,14 +255,14 @@ class Category */ public function getByIds($ids) { - $db = new DB(); + $db = new newznab\db\DB(); return $db->query(sprintf("SELECT concat(cp.title, ' > ',c.title) as title from category c inner join category cp on cp.id = c.parentid where c.id in (%s)", implode(',', $ids))); } public function getNameByID($ID) { - $db = new DB(); + $db = new newznab\db\DB(); $parent = $db->queryOneRow(sprintf("SELECT title FROM category WHERE id = %d", substr($ID, 0, 1) . "000")); $cat = $db->queryOneRow(sprintf("SELECT title FROM category WHERE id = %d", $ID)); @@ -254,7 +274,7 @@ class Category */ public function update($id, $status, $desc, $disablepreview, $minsize, $maxsize) { - $db = new DB(); + $db = new newznab\db\DB(); return $db->queryExec(sprintf("update category set disablepreview = %d, status = %d, minsizetoformrelease = %d, maxsizetoformrelease = %d, description = %s where id = %d", $disablepreview, $status, $minsize, $maxsize, $db->escapeString($desc), $id)); } @@ -264,7 +284,7 @@ class Category */ public function getForMenu($excludedcats = array()) { - $db = new DB(); + $db = new newznab\db\DB(); $ret = array(); $exccatlist = ""; @@ -320,7 +340,7 @@ class Category */ public function get($activeonly = false, $excludedcats = array()) { - $db = new DB(); + $db = new newznab\db\DB(); $exccatlist = ""; if (count($excludedcats) > 0) diff --git a/lib/copy_this/www/lib/console.php b/lib/copy_this/newznab/controllers/console.php similarity index 98% rename from lib/copy_this/www/lib/console.php rename to lib/copy_this/newznab/controllers/console.php index ae2760326..2d7a84987 100644 --- a/lib/copy_this/www/lib/console.php +++ b/lib/copy_this/newznab/controllers/console.php @@ -1,11 +1,7 @@ <?php -require_once(WWW_DIR."/lib/framework/db.php"); -require_once(WWW_DIR."/lib/amazon.php"); -require_once(WWW_DIR."/lib/category.php"); -require_once(WWW_DIR."/lib/genres.php"); -require_once(WWW_DIR."/lib/site.php"); -require_once(WWW_DIR."/lib/util.php"); -require_once(WWW_DIR."/lib/releaseimage.php"); +require_once NN_LIBS . 'AmazonProductAPI.php'; + +use newznab\db\DB; /** * This class looks up metadata about console releases and handles @@ -16,7 +12,7 @@ class Console const NUMTOPROCESSPERTIME = 100; /** - * @var DB + * @var newznab\db\DB */ public $pdo; @@ -38,7 +34,7 @@ class Console $this->pubkey = $site->amazonpubkey; $this->privkey = $site->amazonprivkey; $this->asstag = $site->amazonassociatetag; - $this->pdo = new DB(); + $this->pdo = new newznab\db\DB(); $this->imgSavePath = WWW_DIR.'covers/console/'; } diff --git a/lib/copy_this/www/lib/content.php b/lib/copy_this/newznab/controllers/content.php similarity index 97% rename from lib/copy_this/www/lib/content.php rename to lib/copy_this/newznab/controllers/content.php index 0727348f7..ec94db79e 100644 --- a/lib/copy_this/www/lib/content.php +++ b/lib/copy_this/newznab/controllers/content.php @@ -1,7 +1,6 @@ <?php -require_once(WWW_DIR."/lib/users.php"); -require_once(WWW_DIR."/lib/framework/db.php"); +use newznab\db\DB; /** * This class looks up site content. diff --git a/lib/copy_this/www/lib/episode.php b/lib/copy_this/newznab/controllers/episode.php similarity index 95% rename from lib/copy_this/www/lib/episode.php rename to lib/copy_this/newznab/controllers/episode.php index 00d5d0f59..cc8656679 100644 --- a/lib/copy_this/www/lib/episode.php +++ b/lib/copy_this/newznab/controllers/episode.php @@ -1,5 +1,6 @@ <?php -require_once(WWW_DIR."/lib/framework/db.php"); + +use newznab\db\DB; /** * This class looks up tv episode data. diff --git a/lib/copy_this/www/lib/forum.php b/lib/copy_this/newznab/controllers/forum.php similarity index 98% rename from lib/copy_this/www/lib/forum.php rename to lib/copy_this/newznab/controllers/forum.php index 4f7d7ea71..b8f48017a 100644 --- a/lib/copy_this/www/lib/forum.php +++ b/lib/copy_this/newznab/controllers/forum.php @@ -1,5 +1,6 @@ <?php -require_once(WWW_DIR."/lib/framework/db.php"); + +use newznab\db\DB; /** * This class handles data access for forum and post data. diff --git a/lib/copy_this/www/lib/genres.php b/lib/copy_this/newznab/controllers/genres.php similarity index 96% rename from lib/copy_this/www/lib/genres.php rename to lib/copy_this/newznab/controllers/genres.php index d97f14729..e5d87f0c5 100644 --- a/lib/copy_this/www/lib/genres.php +++ b/lib/copy_this/newznab/controllers/genres.php @@ -1,7 +1,6 @@ <?php -require_once(WWW_DIR . "/lib/framework/db.php"); -require_once(WWW_DIR . "/lib/category.php"); +use newznab\db\DB; class Genres { @@ -13,7 +12,7 @@ class Genres const STATUS_DISABLED = 1; /** - * @var DB; + * @var newznab\db\DB; */ public $pdo; diff --git a/lib/copy_this/www/lib/groups.php b/lib/copy_this/newznab/controllers/groups.php similarity index 98% rename from lib/copy_this/www/lib/groups.php rename to lib/copy_this/newznab/controllers/groups.php index 116760ed7..8d55417e9 100644 --- a/lib/copy_this/www/lib/groups.php +++ b/lib/copy_this/newznab/controllers/groups.php @@ -1,10 +1,6 @@ <?php -require_once(WWW_DIR . "/lib/framework/db.php"); -require_once(WWW_DIR . "/lib/category.php"); -require_once(WWW_DIR . "/lib/site.php"); -require_once(WWW_DIR . "/lib/releases.php"); -require_once(WWW_DIR . "/lib/binaries.php"); -require_once(WWW_DIR . "/lib/releaseimage.php"); + +use newznab\db\DB; /** * This class handles data access for groups. @@ -13,7 +9,7 @@ class Groups { /** - * @var DB + * @var newznab\db\DB */ public $pdo; diff --git a/lib/copy_this/www/lib/install.php b/lib/copy_this/newznab/controllers/install.php similarity index 100% rename from lib/copy_this/www/lib/install.php rename to lib/copy_this/newznab/controllers/install.php diff --git a/lib/copy_this/www/lib/installpage.php b/lib/copy_this/newznab/controllers/installpage.php similarity index 95% rename from lib/copy_this/www/lib/installpage.php rename to lib/copy_this/newznab/controllers/installpage.php index 4ad7dd30f..c4075c53b 100644 --- a/lib/copy_this/www/lib/installpage.php +++ b/lib/copy_this/newznab/controllers/installpage.php @@ -1,5 +1,5 @@ <?php -require_once('../lib/smarty/Smarty.class.php'); +require_once NN_LIBS . 'smarty/Smarty.class.php'; /** * This class represents each page during installation. diff --git a/lib/copy_this/www/lib/menu.php b/lib/copy_this/newznab/controllers/menu.php similarity index 91% rename from lib/copy_this/www/lib/menu.php rename to lib/copy_this/newznab/controllers/menu.php index b88ff7f16..d79a153d5 100644 --- a/lib/copy_this/www/lib/menu.php +++ b/lib/copy_this/newznab/controllers/menu.php @@ -1,6 +1,6 @@ <?php -require_once(WWW_DIR."/lib/framework/db.php"); -require_once(WWW_DIR."/lib/users.php"); + +use newznab\db\DB; /** * This class looks up site menu data. @@ -46,7 +46,7 @@ class Menu */ public function getAll() { - $db = new DB(); + $db = new newznab\db\DB(); return $db->query(sprintf("select * from menu order by role, ordinal")); } @@ -55,7 +55,7 @@ class Menu */ public function getById($id) { - $db = new DB(); + $db = new newznab\db\DB(); return $db->queryOneRow(sprintf("select * from menu where id = %d", $id)); } @@ -64,7 +64,7 @@ class Menu */ public function delete($id) { - $db = new DB(); + $db = new newznab\db\DB(); return $db->queryExec(sprintf("DELETE from menu where id = %d", $id)); } @@ -73,7 +73,7 @@ class Menu */ public function add($menu) { - $db = new DB(); + $db = new newznab\db\DB(); return $db->queryInsert(sprintf("INSERT INTO menu (href, title, tooltip, role, ordinal, menueval, newwindow ) VALUES (%s, %s, %s, %d, %d, %s, %d) ", $db->escapeString($menu["href"]), $db->escapeString($menu["title"]), $db->escapeString($menu["tooltip"]), $menu["role"] , $menu["ordinal"], $db->escapeString($menu["menueval"]), $menu["newwindow"] )); } @@ -83,7 +83,7 @@ class Menu */ public function update($menu) { - $db = new DB(); + $db = new newznab\db\DB(); return $db->queryExec(sprintf("update menu set href = %s, title = %s, tooltip = %s, role = %d, ordinal = %d, menueval = %s, newwindow=%d where id = %d ", $db->escapeString($menu["href"]), $db->escapeString($menu["title"]), $db->escapeString($menu["tooltip"]), $menu["role"] , $menu["ordinal"], $db->escapeString($menu["menueval"]), $menu["newwindow"], $menu["id"] )); } } \ No newline at end of file diff --git a/lib/copy_this/www/lib/movie.php b/lib/copy_this/newznab/controllers/movie.php similarity index 98% rename from lib/copy_this/www/lib/movie.php rename to lib/copy_this/newznab/controllers/movie.php index 9ccdc0c6a..ce01edef1 100644 --- a/lib/copy_this/www/lib/movie.php +++ b/lib/copy_this/newznab/controllers/movie.php @@ -1,12 +1,8 @@ <?php -require_once(WWW_DIR."/lib/framework/db.php"); -require_once(WWW_DIR."/lib/TMDb.php"); -require_once(WWW_DIR."/lib/category.php"); -require_once(WWW_DIR."/lib/nfo.php"); -require_once(WWW_DIR."/lib/site.php"); -require_once(WWW_DIR."/lib/util.php"); -require_once(WWW_DIR."/lib/releaseimage.php"); -require_once(WWW_DIR."/lib/rottentomato.php"); +require_once NN_LIBS . 'TMDb.php'; + +use newznab\db\DB; +use newznab\utility\Utility; /** * This class looks up movie info from external sources and stores/retrieves movieinfo data. @@ -20,7 +16,7 @@ class Movie const SRC_DVD = 5; /** - * @var DB + * @var newznab\db\DB */ public $pdo; @@ -57,7 +53,7 @@ class Movie $site = $s->get(); $this->apikey = $site->tmdbkey; $this->lookuplanguage = $site->lookuplanguage; - $this->pdo = new \DB(); + $this->pdo = new DB(); $this->imgSavePath = WWW_DIR.'covers/movies/'; } @@ -352,7 +348,7 @@ class Movie */ public function getBrowseBy() { - $this->pdo = new Db; + $this->pdo = new newznab\db\DB; $browseby = ' '; $browsebyArr = $this->getBrowseByOptions(); diff --git a/lib/copy_this/www/lib/music.php b/lib/copy_this/newznab/controllers/music.php similarity index 98% rename from lib/copy_this/www/lib/music.php rename to lib/copy_this/newznab/controllers/music.php index aa9ea5ff0..c4d36ae2f 100644 --- a/lib/copy_this/www/lib/music.php +++ b/lib/copy_this/newznab/controllers/music.php @@ -1,11 +1,8 @@ <?php -require_once(WWW_DIR."/lib/framework/db.php"); -require_once(WWW_DIR."/lib/amazon.php"); -require_once(WWW_DIR."/lib/category.php"); -require_once(WWW_DIR."/lib/genres.php"); -require_once(WWW_DIR."/lib/site.php"); -require_once(WWW_DIR."/lib/util.php"); -require_once(WWW_DIR."/lib/releaseimage.php"); +require_once NN_LIBS . 'AmazonProductAPI.php'; + +use newznab\db\DB; +use newznab\utility\Utility; /** * This class looks up music info from external sources and stores/retrieves musicinfo data. @@ -15,7 +12,7 @@ class Music const NUMTOPROCESSPERTIME = 100; /** - * @var DB + * @var newznab\db\DB */ public $pdo; @@ -37,7 +34,7 @@ class Music $this->pubkey = $site->amazonpubkey; $this->privkey = $site->amazonprivkey; $this->asstag = $site->amazonassociatetag; - $this->pdo = new DB(); + $this->pdo = new newznab\db\DB(); $this->imgSavePath = WWW_DIR.'covers/music/'; } @@ -241,7 +238,7 @@ class Music */ public function getBrowseBy() { - $this->pdo = new Db; + $this->pdo = new newznab\db\DB; $browseby = ' '; $browsebyArr = $this->getBrowseByOptions(); diff --git a/lib/namefixer.php b/lib/copy_this/newznab/controllers/namefixer.php similarity index 98% rename from lib/namefixer.php rename to lib/copy_this/newznab/controllers/namefixer.php index 3b6c4a2d4..f43ddf826 100644 --- a/lib/namefixer.php +++ b/lib/copy_this/newznab/controllers/namefixer.php @@ -1,20 +1,8 @@ <?php -require_once(dirname(__FILE__) . "/../bin/config.php"); -require_once(WWW_DIR . "lib/framework/db.php"); -require_once(WWW_DIR . "lib/category.php"); -require_once(WWW_DIR . "lib/Categorize.php"); -require_once(WWW_DIR . "lib/nzb.php"); -require_once(WWW_DIR . "lib/groups.php"); -require_once(WWW_DIR . "lib/nntp.php"); -require_once(WWW_DIR . "/lib/ReleaseSearch.php"); -require_once(WWW_DIR . "/lib/ColorCLI.php"); -require_once(WWW_DIR . "/lib/ConsoleTools.php"); -require_once (NN_LIB . 'SphinxSearch.php'); -require_once (NN_LIB . 'ReleaseCleaning.php'); -require_once("nzbcontents.php"); -require_once("Info.php"); -require_once("Pprocess.php"); +use newznab\db\DB; +use \newznab\processing\PProcess; +use newznab\utility\Utility; //This script is ported from nZEDb and adapted for newznab @@ -106,7 +94,7 @@ class NameFixer protected $fullall; /** - * @var DB + * @var newznab\db\DB */ public $pdo; diff --git a/lib/copy_this/www/lib/nfo.php b/lib/copy_this/newznab/controllers/nfo.php similarity index 98% rename from lib/copy_this/www/lib/nfo.php rename to lib/copy_this/newznab/controllers/nfo.php index bdb117c45..6f3121eeb 100644 --- a/lib/copy_this/www/lib/nfo.php +++ b/lib/copy_this/newznab/controllers/nfo.php @@ -1,10 +1,6 @@ <?php -require_once(WWW_DIR."/lib/framework/db.php"); -require_once(WWW_DIR."/lib/movie.php"); -require_once(WWW_DIR."/lib/tvrage.php"); -require_once(WWW_DIR."/lib/nntp.php"); -require_once(WWW_DIR."/lib/nzb.php"); -require_once(WWW_DIR."/lib/nzbinfo.php"); + +use newznab\db\DB; // Silent Error Handler (used to shut up noisy XML exceptions) function nfoHandleError($errno, $errstr, $errfile, $errline, array $errcontext){ diff --git a/lib/copy_this/www/lib/nntp.php b/lib/copy_this/newznab/controllers/nntp.php similarity index 98% rename from lib/copy_this/www/lib/nntp.php rename to lib/copy_this/newznab/controllers/nntp.php index ada49c8bf..2edc46f3a 100644 --- a/lib/copy_this/www/lib/nntp.php +++ b/lib/copy_this/newznab/controllers/nntp.php @@ -2,14 +2,8 @@ /** * Attempt to include PEAR's nntp class if it has not already been included. */ -require_once(WWW_DIR . "/lib/Net_NNTP/NNTP/Client.php"); -require_once(WWW_DIR . "/lib/framework/db.php"); -require_once(WWW_DIR . "/lib/Tmux.php"); -require_once(WWW_DIR . "/lib/site.php"); -require_once(WWW_DIR . "/lib/util.php"); -require_once(WWW_DIR . "/lib/binaries.php"); -require_once(WWW_DIR . "/lib/ColorCLI.php"); -require_once(WWW_DIR . "/lib/Logger.php"); +require_once NN_LIBS . 'Net_NNTP/NNTP/Client.php'; + /** * Class for connecting to the usenet, retrieving articles and article headers, @@ -113,7 +107,7 @@ class NNTP extends Net_NNTP_Client $this->_echo = ($options['Echo'] && NN_ECHOCLI); - $this->pdo = ($options['Settings'] instanceof \DB ? $options['Settings'] : new \DB()); + $this->pdo = ($options['Settings'] instanceof \newznab\db\DB ? $options['Settings'] : new \newznab\db\DB()); $s = new Sites(); $this->site = $s->get(); @@ -1161,7 +1155,7 @@ class NNTP extends Net_NNTP_Client $ouFile = $this->_yEncTempOutput . mt_rand(0, 999999); file_put_contents($inFile, $input[1]); file_put_contents($ouFile, ''); - runCmd( + \newznab\utility\Utility::runCmd( "'" . $this->_yyDecoderPath . "' '" . @@ -1235,7 +1229,7 @@ class NNTP extends Net_NNTP_Client } } else if ($this->_yyDecoderPath !== false) { - $this->_yEncSilence = (isWindows() ? '' : ' > /dev/null 2>&1'); + $this->_yEncSilence = (\newznab\utility\Utility::isWindows() ? '' : ' > /dev/null 2>&1'); $this->_yEncTempInput = NN_TMP . 'yEnc' . DS; $this->_yEncTempOutput = $this->_yEncTempInput . 'output'; $this->_yEncTempInput .= 'input'; diff --git a/lib/copy_this/www/lib/nzb.php b/lib/copy_this/newznab/controllers/nzb.php similarity index 97% rename from lib/copy_this/www/lib/nzb.php rename to lib/copy_this/newznab/controllers/nzb.php index 635338df0..da6c7d8c0 100644 --- a/lib/copy_this/www/lib/nzb.php +++ b/lib/copy_this/newznab/controllers/nzb.php @@ -1,7 +1,6 @@ <?php -require_once(WWW_DIR . "/lib/framework/db.php"); -require_once(WWW_DIR . "/lib/site.php"); -require_once(WWW_DIR . "/lib/category.php"); + +use newznab\db\DB; /** * Class for reading and writing NZB files on the hard disk, @@ -37,7 +36,7 @@ class NZB /** * Instance of class db. - * @var \DB + * @var \newznab\db\DB * @access public */ public $pdo; @@ -83,13 +82,13 @@ class NZB /** * Default constructor. * - * @param \DB $pdo + * @param \newznab\db\DB $pdo * * @access public */ public function __construct(&$pdo = null) { - $this->pdo = ($pdo instanceof \DB ? $pdo : new \DB()); + $this->pdo = ($pdo instanceof DB ? $pdo : new DB()); $s = new Sites(); $this->site = $s->get(); diff --git a/lib/nzbcontents.php b/lib/copy_this/newznab/controllers/nzbcontents.php similarity index 94% rename from lib/nzbcontents.php rename to lib/copy_this/newznab/controllers/nzbcontents.php index 3352a746e..3ca9ef6a6 100644 --- a/lib/nzbcontents.php +++ b/lib/copy_this/newznab/controllers/nzbcontents.php @@ -1,12 +1,8 @@ <?php -require_once(WWW_DIR."/lib/framework/db.php"); -require_once(WWW_DIR."/lib/nntp.php"); -require_once(WWW_DIR . "/lib/nzb.php"); -require_once(WWW_DIR."/lib/Tmux.php"); -require_once(WWW_DIR . "/lib/util.php"); -require_once(WWW_DIR . "/lib/ColorCLI.php"); -require_once("Info.php"); -require_once("Pprocess.php"); + +use newznab\db\DB; +use \newznab\processing\PProcess; +use newznab\utility\Utility; /** * Gets information contained within the NZB. @@ -16,7 +12,7 @@ require_once("Pprocess.php"); Class NZBContents { /** - * @var DB + * @var newznab\db\DB * @access protected */ public $pdo; @@ -72,7 +68,7 @@ Class NZBContents * 'NNTP' => NNTP ; Class NNTP. * 'Nfo' => Nfo ; Class Info. * 'NZB' => NZB ; Class NZB. - * 'Settings' => DB ; Class DB. + * 'Settings' => DB ; Class newznab\db\DB. * 'PostProcess' => PProcess ; Class PProcess. * ) * @@ -91,7 +87,7 @@ Class NZBContents $options += $defaults; $this->echooutput = ($options['Echo'] && NN_ECHOCLI); - $this->pdo = ($options['Settings'] instanceof \DB ? $options['Settings'] : new \DB()); + $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); $this->nntp = ($options['NNTP'] instanceof \NNTP ? $options['NNTP'] : new \NNTP(['Echo' => $this->echooutput, 'Settings' => $this->pdo])); $this->nfo = ($options['Nfo'] instanceof \Info ? $options['Nfo'] : new \Info(['Echo' => $this->echooutput, 'Settings' => $this->pdo])); $this->pp = ( diff --git a/lib/copy_this/www/lib/nzbinfo.php b/lib/copy_this/newznab/controllers/nzbinfo.php similarity index 99% rename from lib/copy_this/www/lib/nzbinfo.php rename to lib/copy_this/newznab/controllers/nzbinfo.php index 5a4a4100a..80c795c9f 100644 --- a/lib/copy_this/www/lib/nzbinfo.php +++ b/lib/copy_this/newznab/controllers/nzbinfo.php @@ -1,6 +1,6 @@ <?php -class nzbInfo +class NZBInfo { public $source = ''; public $metadata = []; diff --git a/lib/copy_this/www/lib/nzbvortex.php b/lib/copy_this/newznab/controllers/nzbvortex.php similarity index 100% rename from lib/copy_this/www/lib/nzbvortex.php rename to lib/copy_this/newznab/controllers/nzbvortex.php diff --git a/lib/copy_this/www/lib/page.php b/lib/copy_this/newznab/controllers/page.php similarity index 88% rename from lib/copy_this/www/lib/page.php rename to lib/copy_this/newznab/controllers/page.php index 68b06ea5e..0e2c801aa 100644 --- a/lib/copy_this/www/lib/page.php +++ b/lib/copy_this/newznab/controllers/page.php @@ -1,10 +1,4 @@ <?php -require_once(WWW_DIR."/lib/framework/basepage.php"); -require_once(WWW_DIR."/lib/content.php"); -require_once(WWW_DIR."/lib/category.php"); -require_once(WWW_DIR."/lib/users.php"); -require_once(WWW_DIR."/lib/forum.php"); -require_once(WWW_DIR."/lib/menu.php"); /** * This class represents every normal user page in the site. diff --git a/lib/copy_this/www/lib/parsing.php b/lib/copy_this/newznab/controllers/parsing.php similarity index 99% rename from lib/copy_this/www/lib/parsing.php rename to lib/copy_this/newznab/controllers/parsing.php index d12d3e36e..9380adde8 100644 --- a/lib/copy_this/www/lib/parsing.php +++ b/lib/copy_this/newznab/controllers/parsing.php @@ -1,14 +1,6 @@ <?php -require_once(WWW_DIR . "/lib/framework/db.php"); -require_once(WWW_DIR . "/lib/site.php"); -require_once(WWW_DIR . "/lib/category.php"); -require_once(WWW_DIR . "/lib/movie.php"); -require_once(WWW_DIR . "/lib/releases.php"); -require_once(WWW_DIR . "/lib/nzb.php"); -require_once(WWW_DIR . "/lib/nzbinfo.php"); -require_once(WWW_DIR . "/lib/nntp.php"); -require_once(WWW_DIR . "/lib/rarinfo/par2info.php"); -require_once(WWW_DIR . "/lib/ColorCLI.php"); + +use newznab\db\DB; /** * This class handles parsing misc>other releases into real names. @@ -16,7 +8,7 @@ require_once(WWW_DIR . "/lib/ColorCLI.php"); class Parsing { /** - * @var DB + * @var newznab\db\DB */ public $pdo; @@ -43,7 +35,7 @@ class Parsing $this->cleanup = ['nuke' => [], 'misc' => []]; $s = new Sites(); $this->site = $s->get(); - $this->pdo = new DB(); + $this->pdo = new newznab\db\DB(); } /** diff --git a/lib/copy_this/www/lib/postprocess.php b/lib/copy_this/newznab/controllers/postprocess.php similarity index 95% rename from lib/copy_this/www/lib/postprocess.php rename to lib/copy_this/newznab/controllers/postprocess.php index f84d02f65..17519cf91 100644 --- a/lib/copy_this/www/lib/postprocess.php +++ b/lib/copy_this/newznab/controllers/postprocess.php @@ -1,25 +1,9 @@ <?php -require_once(WWW_DIR."/lib/framework/db.php"); -require_once(WWW_DIR."/lib/site.php"); -require_once(WWW_DIR."/lib/util.php"); -require_once(WWW_DIR."/lib/releases.php"); -require_once(WWW_DIR."/lib/rarinfo/archiveinfo.php"); -require_once(WWW_DIR."/lib/releasefiles.php"); -require_once(WWW_DIR."/lib/releaseextra.php"); -require_once(WWW_DIR."/lib/releaseimage.php"); -require_once(WWW_DIR."/lib/tvrage.php"); -require_once(WWW_DIR."/lib/thetvdb.php"); -require_once(WWW_DIR."/lib/anidb.php"); -require_once(WWW_DIR."/lib/movie.php"); -require_once(WWW_DIR."/lib/music.php"); -require_once(WWW_DIR."/lib/console.php"); -require_once(WWW_DIR."/lib/nfo.php"); -require_once(WWW_DIR."/lib/category.php"); -require_once(WWW_DIR."/lib/book.php"); -require_once(WWW_DIR."/lib/Books.php"); -require_once(WWW_DIR."/lib/nzbinfo.php"); -require_once(WWW_DIR."/lib/spotnab.php"); -require_once(WWW_DIR."/lib/parsing.php"); +require_once NN_LIBS . 'rarinfo/par2info.php'; +require_once NN_LIBS . 'rarinfo/archiveinfo.php'; + +use newznab\db\DB; +use newznab\utility\Utility; /** * This class handles all post processing performed during update_releases process. @@ -28,7 +12,7 @@ class PostProcess { /** - * @var DB + * @var newznab\db\DB */ public $pdo; @@ -47,7 +31,7 @@ class PostProcess $this->echooutput = (NN_ECHOCLI && $echooutput);; $s = new \Sites(); $this->site = $s->get(); - $this->pdo = new \DB(); + $this->pdo = new DB(); $this->mediafileregex = 'AVI|VOB|MKV|MP4|TS|WMV|MOV|M4V|F4V|MPG|MPEG|M2TS'; $this->audiofileregex = 'MP3|AAC|OGG'; $this->mp3SavePath = WWW_DIR.'covers/audio/'; @@ -329,7 +313,6 @@ class PostProcess */ public function processAdditional($numtoProcess = 100) { - require_once(WWW_DIR."/lib/nntp.php"); $maxattemptstocheckpassworded = 5; $processVideoSample = ($this->site->ffmpegpath != '') ? true : false; @@ -538,7 +521,7 @@ class PostProcess $rarfile = $tmpPath.'rarfile.rar'; file_put_contents($rarfile, $fetchedBinary); $execstring = '"'.$this->site->unrarpath.'" e -ai -ep -c- -id -r -kb -p- -y -inul "'.$rarfile.'" "'.$tmpPath.'"'; - $output = runCmd($execstring, false, true); + $output = Utility::runCmd($execstring, false, true); unlink($rarfile); } @@ -612,7 +595,7 @@ class PostProcess public function processReleaseFiles($fetchedBinary, $relid) { $retval = array(); - $rar = new ArchiveInfo(); + $rar = new \ArchiveInfo(); $rf = new ReleaseFiles; $rar->setData($fetchedBinary, true); @@ -707,7 +690,7 @@ class PostProcess } $execstring = '"'.$unrarPath.'" e -ai -ep -c- -id -r -kb -p- -y -inul "'.$rarfile.'" "'.$tmpPath.'"'; - $output = runCmd($execstring, false, true); + $output = Utility::runCmd($execstring, false, true); // delete the rar @unlink($rarfile); @@ -738,7 +721,7 @@ class PostProcess } $execstring = '"'.$unrarPath.'" e -ai -ep -c- -id -r -kb -p- -y -inul "'.$tmpPath.$israr[$i].'" "'.$tmpPath.'"'; - $output2 = runCmd($execstring, false, true); + $output2 = Utility::runCmd($execstring, false, true); @unlink($tmpPath.$israr[$i]); } else @@ -819,7 +802,7 @@ class PostProcess if (preg_match("/\.(".$this->mediafileregex.'|'.$this->audiofileregex.")$/i",$mediafile)) { $execstring = '"'.$mediainfo.'" --Output=XML "'.$mediafile.'"'; - $xmlarray = runCmd($execstring); + $xmlarray = Utility::runCmd($execstring); if (is_array($xmlarray)) { @@ -870,7 +853,7 @@ class PostProcess //1.x $execstring = '"'.$ffmpeginfo.'" -q:v 0 -i "'.$samplefile.'" -vframes 300 "'.$ramdrive.'zzzz%03d.jpg"'; - runCmd($execstring, false, true); + Utility::runCmd($execstring, false, true); $all_files = scandir($ramdrive,1); if(preg_match("/zzzz\d{3}\.jpg/",$all_files[1])) { @@ -917,8 +900,8 @@ class PostProcess $execstring = '"'.$lameinfo.'" -b 96 "'.$samplefile.'" "'.$outfile.'"'; $execstringogg = '"'.$ffmpeginfo.'" -i "'.$samplefile.'" -acodec libvorbis "'.$outfileogg.'"'; - $output = runCmd($execstring, false, true); - $output = runCmd($execstringogg, false, true); + $output = Utility::runCmd($execstring, false, true); + $output = Utility::runCmd($execstringogg, false, true); // // lame can create bad/small files if the source was corrupt diff --git a/lib/copy_this/www/lib/powerprocess.php b/lib/copy_this/newznab/controllers/powerprocess.php similarity index 100% rename from lib/copy_this/www/lib/powerprocess.php rename to lib/copy_this/newznab/controllers/powerprocess.php diff --git a/lib/copy_this/www/lib/predb.php b/lib/copy_this/newznab/controllers/predb.php similarity index 98% rename from lib/copy_this/www/lib/predb.php rename to lib/copy_this/newznab/controllers/predb.php index a434395ce..9d16e13e4 100644 --- a/lib/copy_this/www/lib/predb.php +++ b/lib/copy_this/newznab/controllers/predb.php @@ -1,7 +1,7 @@ <?php -require_once(WWW_DIR."/lib/framework/db.php"); -require_once(WWW_DIR."/lib/site.php"); -require_once(WWW_DIR."/lib/sphinx.php"); + +use newznab\db\DB; + /** * This class handles lookup of nzpre lookups and storage/retrieval of pre data. @@ -9,7 +9,7 @@ require_once(WWW_DIR."/lib/sphinx.php"); class PreDB { /** - * @var DB + * @var newznab\db\DB */ public $pdo; @@ -26,7 +26,7 @@ class PreDB public function __construct($echooutput = true) { $this->echooutput = (NN_ECHOCLI && $echooutput); - $this->pdo = new \DB(); + $this->pdo = new DB(); } /** diff --git a/lib/prehash.php b/lib/copy_this/newznab/controllers/prehash.php similarity index 94% rename from lib/prehash.php rename to lib/copy_this/newznab/controllers/prehash.php index ca3b30ea4..71fdf7b10 100644 --- a/lib/prehash.php +++ b/lib/copy_this/newznab/controllers/prehash.php @@ -1,15 +1,7 @@ <?php -require_once(WWW_DIR."lib/framework/db.php"); -require_once(WWW_DIR."lib/groups.php"); -require_once(WWW_DIR."lib/nfo.php"); -require_once(WWW_DIR."lib/site.php"); -require_once(WWW_DIR . "/lib/ConsoleTools.php"); -require_once(WWW_DIR . "/lib/ColorCLI.php"); -require_once("nzbcontents.php"); -require_once("simple_html_dom.php"); -require_once("IRCScraper.php"); -require_once("Info.php"); -require_once("namefixer.php"); +require_once NN_LIBS . 'simple_html_dom.php'; + +use newznab\db\DB; /** * Class for inserting names/categories etc from PreDB sources into the DB, @@ -38,7 +30,7 @@ Class PreHash protected $echooutput; /** - * @var DB + * @var newznab\db\DB */ protected $pdo; diff --git a/lib/copy_this/www/lib/recaptchalib.php b/lib/copy_this/newznab/controllers/recaptchalib.php similarity index 100% rename from lib/copy_this/www/lib/recaptchalib.php rename to lib/copy_this/newznab/controllers/recaptchalib.php diff --git a/lib/copy_this/www/lib/releasecomments.php b/lib/copy_this/newznab/controllers/releasecomments.php similarity index 98% rename from lib/copy_this/www/lib/releasecomments.php rename to lib/copy_this/newznab/controllers/releasecomments.php index 942757ff8..3dde85184 100644 --- a/lib/copy_this/www/lib/releasecomments.php +++ b/lib/copy_this/newznab/controllers/releasecomments.php @@ -1,6 +1,7 @@ <?php -require_once(WWW_DIR."/lib/framework/db.php"); -require_once(WWW_DIR."/lib/site.php"); + +use newznab\db\DB; + /** * This class handles storage and retrieval of release comments. diff --git a/lib/copy_this/www/lib/releaseextra.php b/lib/copy_this/newznab/controllers/releaseextra.php similarity index 98% rename from lib/copy_this/www/lib/releaseextra.php rename to lib/copy_this/newznab/controllers/releaseextra.php index 240e09c4f..f43253444 100644 --- a/lib/copy_this/www/lib/releaseextra.php +++ b/lib/copy_this/newznab/controllers/releaseextra.php @@ -1,6 +1,6 @@ <?php -require_once(WWW_DIR . "/lib/framework/db.php"); -require_once(WWW_DIR . "/lib/util.php"); + +use newznab\db\DB; /** * This class handles storage and retrieval of releaseextrafull/releasevideo/audio/subs data. @@ -67,7 +67,7 @@ class ReleaseExtra public function addFromXml($releaseID, $xml) { $xmlObj = @simplexml_load_string($xml); - $arrXml = objectsIntoArray($xmlObj); + $arrXml = \newznab\utility\Utility::objectsIntoArray($xmlObj); $containerformat = ""; $overallbitrate = ""; diff --git a/lib/copy_this/www/lib/releasefiles.php b/lib/copy_this/newznab/controllers/releasefiles.php similarity index 96% rename from lib/copy_this/www/lib/releasefiles.php rename to lib/copy_this/newznab/controllers/releasefiles.php index df5f23049..0bd9b9321 100644 --- a/lib/copy_this/www/lib/releasefiles.php +++ b/lib/copy_this/newznab/controllers/releasefiles.php @@ -1,5 +1,6 @@ <?php -require_once(WWW_DIR."/lib/framework/db.php"); + +use newznab\db\DB; /** * This class handles storage and retrieval of releasefiles. diff --git a/lib/copy_this/www/lib/releaseimage.php b/lib/copy_this/newznab/controllers/releaseimage.php similarity index 97% rename from lib/copy_this/www/lib/releaseimage.php rename to lib/copy_this/newznab/controllers/releaseimage.php index ce53c852a..4ae6e0e5d 100644 --- a/lib/copy_this/www/lib/releaseimage.php +++ b/lib/copy_this/newznab/controllers/releaseimage.php @@ -1,6 +1,7 @@ <?php -require_once(WWW_DIR . "/lib/framework/db.php"); -require_once(WWW_DIR . "/lib/util.php"); + +use newznab\db\DB; +use newznab\utility\Utility; /** * Resize/save/delete images to disk. @@ -52,7 +53,7 @@ class ReleaseImage { // Creates the NN_COVERS constant if ($pdo === null) { - $pdo = new \DB(); + $pdo = new DB(); } // Table | Column $this->audSavePath = NN_COVERS . 'audiosample' . DS; // releases guid diff --git a/lib/copy_this/www/lib/releaseregex.php b/lib/copy_this/newznab/controllers/releaseregex.php similarity index 98% rename from lib/copy_this/www/lib/releaseregex.php rename to lib/copy_this/newznab/controllers/releaseregex.php index 3efd34dc8..2e4da897b 100644 --- a/lib/copy_this/www/lib/releaseregex.php +++ b/lib/copy_this/newznab/controllers/releaseregex.php @@ -1,9 +1,6 @@ <?php -require_once(WWW_DIR . "/lib/framework/db.php"); -require_once(WWW_DIR . "/lib/binaries.php"); -require_once(WWW_DIR . "/lib/groups.php"); -require_once(WWW_DIR . "/lib/nntp.php"); -require_once(WWW_DIR . "/lib/site.php"); + +use newznab\db\DB; /** diff --git a/lib/copy_this/www/lib/releases.php b/lib/copy_this/newznab/controllers/releases.php similarity index 99% rename from lib/copy_this/www/lib/releases.php rename to lib/copy_this/newznab/controllers/releases.php index c819b403a..13e5a68f9 100644 --- a/lib/copy_this/www/lib/releases.php +++ b/lib/copy_this/newznab/controllers/releases.php @@ -1,14 +1,7 @@ <?php -require_once(WWW_DIR . "/lib/framework/db.php"); -require_once(WWW_DIR . "lib/category.php"); -require_once(WWW_DIR . "lib/site.php"); -require_once(WWW_DIR . "lib/zipfile.php"); -require_once(WWW_DIR . "lib/nzb.php"); -require_once(WWW_DIR . "lib/SphinxSearch.php"); -require_once(WWW_DIR . "lib/ReleaseSearch.php"); -require_once(WWW_DIR . "lib/groups.php"); -require_once(WWW_DIR . "lib/releaseimage.php"); -require_once(WWW_DIR . "/lib/util.php"); + +use newznab\db\DB; +use newznab\utility\Utility; /** * Class Releases @@ -22,7 +15,7 @@ class Releases const PASSWD_RAR = 10; // Definitely passworded. /** - * @var DB + * @var newznab\db\DB */ public $pdo; diff --git a/lib/copy_this/www/lib/rottentomato.php b/lib/copy_this/newznab/controllers/rottentomato.php similarity index 99% rename from lib/copy_this/www/lib/rottentomato.php rename to lib/copy_this/newznab/controllers/rottentomato.php index 159f8a2e4..1ee16f710 100644 --- a/lib/copy_this/www/lib/rottentomato.php +++ b/lib/copy_this/newznab/controllers/rottentomato.php @@ -1,5 +1,6 @@ <?php -require_once(WWW_DIR."/lib/util.php"); + +use newznab\utility\Utility; /** * Fetches and returns JSON documents from the Rotten Tomato API using a supplied API key. diff --git a/lib/copy_this/www/lib/sabnzbd.php b/lib/copy_this/newznab/controllers/sabnzbd.php similarity index 99% rename from lib/copy_this/www/lib/sabnzbd.php rename to lib/copy_this/newznab/controllers/sabnzbd.php index 3dcaafe90..933f1c86e 100644 --- a/lib/copy_this/www/lib/sabnzbd.php +++ b/lib/copy_this/newznab/controllers/sabnzbd.php @@ -1,5 +1,6 @@ <?php -require_once(WWW_DIR . "/lib/util.php"); + +use newznab\utility\Utility; /** * Class SABnzbd diff --git a/lib/copy_this/www/lib/showsleep.php b/lib/copy_this/newznab/controllers/showsleep.php similarity index 100% rename from lib/copy_this/www/lib/showsleep.php rename to lib/copy_this/newznab/controllers/showsleep.php diff --git a/lib/copy_this/www/lib/site.php b/lib/copy_this/newznab/controllers/site.php similarity index 97% rename from lib/copy_this/www/lib/site.php rename to lib/copy_this/newznab/controllers/site.php index ae436ce3e..4e60516c4 100644 --- a/lib/copy_this/www/lib/site.php +++ b/lib/copy_this/newznab/controllers/site.php @@ -1,6 +1,7 @@ <?php -require_once(WWW_DIR . "/lib/framework/db.php"); -require_once(WWW_DIR . "/lib/framework/cache.php"); + +use newznab\db\DB; +use newznab\libraries\Cache; class Sites { diff --git a/lib/copy_this/www/lib/sphinx.php b/lib/copy_this/newznab/controllers/sphinx.php similarity index 98% rename from lib/copy_this/www/lib/sphinx.php rename to lib/copy_this/newznab/controllers/sphinx.php index 0f5efe0e0..f0935a71f 100644 --- a/lib/copy_this/www/lib/sphinx.php +++ b/lib/copy_this/newznab/controllers/sphinx.php @@ -8,12 +8,8 @@ */ if (!defined("FS_ROOT")) { define('FS_ROOT', realpath(dirname(__FILE__))); } -require_once(FS_ROOT."/../../www/config.php"); -require_once(FS_ROOT."/../../www/lib/framework/db.php"); -require_once(FS_ROOT."/../../www/lib/category.php"); -require_once(FS_ROOT."/../../www/lib/nzb.php"); -require_once(FS_ROOT."/../../www/lib/releasefiles.php"); -require_once(FS_ROOT."/../../www/lib/util.php"); + +use newznab\libraries\Cache; // Every day define("INDEX_MERGE_FREQ", 1440); @@ -55,9 +51,9 @@ class Sphinx $output = array(); $handle = popen($cmd, "r"); while ($line = fgets($handle)) { - if (startsWith($line, "Sphinx") || - startsWith($line, "Copyright") || - startsWith($line, "\n") || startsWith($line, "using config")) + if (\newznab\utility\Utility::startsWith($line, "Sphinx") || + \newznab\utility\Utility::startsWith($line, "Copyright") || + \newznab\utility\Utility::startsWith($line, "\n") || startsWith($line, "using config")) { continue; } @@ -111,7 +107,7 @@ class Sphinx return false; } - $db = new DB(); + $db = new newznab\db\DB(); if ($lastRebuildDate == 0) { $lastRebuildDate = "NOW()"; @@ -149,7 +145,7 @@ class Sphinx return false; } - $db = new DB(); + $db = new newznab\db\DB(); if ($lastMergedDate == 0) { $lastMergedDate = "NOW()"; @@ -309,7 +305,7 @@ class Sphinx */ public function update() { - $db = new DB(); + $db = new newznab\db\DB(); if (!$this->site->sphinxenabled) { // Sphinx is disabled, so we don't do anything. @@ -545,7 +541,7 @@ class Sphinx } // Get connection to Newznab's MySQL database - $ndb = new DB; + $ndb = new newznab\db\DB; // Determine which release to start with if ($startingID < 0) { @@ -679,7 +675,7 @@ class Sphinx } if ($lookupQuery && count($results) > 0) { - $ndb = new DB; + $ndb = new newznab\db\DB; $sql = sprintf($lookupQuery, implode(",", $results)); $result = $ndb->queryDirect($sql); if ($result) @@ -725,7 +721,7 @@ class Sphinx $indexes=array(), $lookup=true, $where=array(), &$lookupQuery="") { - $ndb = new DB; + $ndb = new newznab\db\DB; $offset = intval($offset); $limit = intval($limit); @@ -974,7 +970,7 @@ class Sphinx $limit=100, $name="", $cat=array(-1), $maxage=-1, $indexes=array(), $lookup=true) { - $db = new DB(); + $db = new newznab\db\DB(); $order = array("postdate", "desc"); $search = array($name); if ($series != "") { @@ -1040,7 +1036,7 @@ class Sphinx $cat=array(-1), $genre="", $maxage=-1, $indexes=array(), $lookup=true) { - $db = new DB(); + $db = new newznab\db\DB(); $search = array(); $order = array("postdate", "desc"); $where = array(); @@ -1107,7 +1103,7 @@ class Sphinx $cat=array(-1), $maxage=-1, $indexes=array(), $lookup=true) { - $db = new DB(); + $db = new newznab\db\DB(); $search = array(); $where = array(); $order = array("postdate", "desc"); @@ -1183,7 +1179,7 @@ class Sphinx public function searchBook($author, $title, $offset=0, $limit=100, $maxage=-1, $indexes=array(), $lookup=true) { - $db = new DB(); + $db = new newznab\db\DB(); $order = array("postdate", "desc"); $search = array(); if ($author != "") { @@ -1246,7 +1242,7 @@ class Sphinx $name='', $maxage=-1, $indexes=array(), $lookup=true) { - $db = new DB(); + $db = new newznab\db\DB(); $where = array(); $search = array(); $order = array("postdate", "desc"); @@ -1295,7 +1291,7 @@ class Sphinx */ public function getPreRange($start=0, $num, $dirname='', $category='') { - $db = new DB(); + $db = new newznab\db\DB(); $dirname = empty($category) ? $dirname : $dirname." @category =".$category; $sphinxQuery = sprintf("SELECT id " ."FROM predb, predb_delta " diff --git a/lib/copy_this/www/lib/spotnab.php b/lib/copy_this/newznab/controllers/spotnab.php similarity index 98% rename from lib/copy_this/www/lib/spotnab.php rename to lib/copy_this/newznab/controllers/spotnab.php index 09ca4e979..d15dd9bde 100644 --- a/lib/copy_this/www/lib/spotnab.php +++ b/lib/copy_this/newznab/controllers/spotnab.php @@ -1,14 +1,6 @@ <?php -require_once(WWW_DIR."/lib/framework/db.php"); -require_once(WWW_DIR."/lib/nntp.php"); -require_once(WWW_DIR."/lib/nzb.php"); -require_once(WWW_DIR."/lib/site.php"); -require_once(WWW_DIR."/lib/releases.php"); -require_once(WWW_DIR."/lib/releasecomments.php"); -require_once(WWW_DIR."/lib/releaseimage.php"); -require_once(WWW_DIR."/lib/nzbinfo.php"); -require_once(WWW_DIR."/lib/util.php"); -require_once(WWW_DIR."/lib/users.php"); + +use newznab\db\DB; // Help out those who don't have SSL enabled if(!defined('OPENSSL_KEYTYPE_RSA')) { @@ -272,7 +264,7 @@ class SpotNab { // *********************************************************************** public function auto_clean($max_days=90){ - $db = new DB(); + $db = new newznab\db\DB(); // automatically sweep old sources lingering that have not shown any // sort of life what-so-ever for more then 90 days $sql = "DELETE FROM spotnabsources WHERE " @@ -296,7 +288,7 @@ class SpotNab { $sql_rel = "SELECT GID FROM releases WHERE GID IN ('%s') "; $sql_del = "DELETE FROM releasecomment WHERE GID IN ('%s')"; $total_delcnt = 0; - $db = new DB(); + $db = new newznab\db\DB(); while(1) { $res = $db->query(sprintf($sql, $offset, $batch)); @@ -341,7 +333,7 @@ class SpotNab { // using existing sources // - it has never posted discovery information // - it has never scanned for existing discoveries - $db = new DB(); + $db = new newznab\db\DB(); // resets sources so they need to query again $sources = "UPDATE spotnabsources SET " @@ -375,7 +367,7 @@ class SpotNab { // *********************************************************************** public function fetch_discovery($reftime=Null, $retries=3){ - $db = new DB(); + $db = new newznab\db\DB(); $last = $first = Null; // Return Value; Initialize it to Okay @@ -423,7 +415,7 @@ class SpotNab { echo "Spotnab : Discovery "; $summary = $this->_nntp->selectGroup( SpotNab::AUTODISCOVER_POST_GROUP); - while(PEAR::isError($summary)) + while(NNTP::isError($summary)) { // Reset Connection (This happens first time // around since _nntpReset() will perform @@ -537,7 +529,7 @@ class SpotNab { // *********************************************************************** public function auto_post_discovery($repost_sec=SpotNab::POST_BROADCAST_INTERVAL){ - $db = new DB(); + $db = new newznab\db\DB(); // performs a post discovery once the time in seconds has elapsed $q = "SELECT updateddate FROM site WHERE " ."setting = 'spotnabbroadcast'"; @@ -660,7 +652,7 @@ class SpotNab { * The specified $reftime is presumed to be local *not utc* */ - $db = new DB(); + $db = new newznab\db\DB(); $last = $first = Null; // Return Value; Initialize it to Okay @@ -797,7 +789,7 @@ class SpotNab { printf("Spotnab : %d source(s)...", count($hash)); $summary = $this->_nntp->selectGroup($group); - while(PEAR::isError($summary)) + while(NNTP::isError($summary)) { // Reset Connection (This happens first time // around since _nntpReset() will perform @@ -913,7 +905,7 @@ class SpotNab { public function processGID($limit=500, $batch=5000, $delete_broken_releases=false){ // Process until someone presses cntrl-c - $db = new DB(); + $db = new newznab\db\DB(); $nzb = new NZB(); $processed = 0; @@ -1015,7 +1007,7 @@ class SpotNab { public function keygen($print=true, $force_regen=false){ // Simply generate a Public/Private Key pair if they don't already // exist - $db = new DB(); + $db = new newznab\db\DB(); // A small boolean we safely toggle after performing // a few checks first to make sure it's safe to do so @@ -1130,7 +1122,7 @@ class SpotNab { while(($retries > 0) && ($interval > 0)){ $summary = $this->_nntp->selectGroup($group); - if(PEAR::isError($summary)) + if(NNTP::isError($summary)) { // Reset Connection $this->_nntpReset(); @@ -1338,7 +1330,7 @@ class SpotNab { // Prepare some general SQL Commands for saving later if all goes well // - $db = new DB(); + $db = new newznab\db\DB(); $rc = new ReleaseComments(); // Comments @@ -1561,7 +1553,7 @@ class SpotNab { // Prepare some general SQL Commands for saving later if all goes well // - $db = new DB(); + $db = new newznab\db\DB(); // Auto Enable Flag (used for inserts only) $auto_enable = ($this->_auto_enable)?"1":"0"; @@ -1751,7 +1743,7 @@ class SpotNab { do { $raw = $this->_nntp->getBody("<".$id.">", true); - if(PEAR::isError($raw)) + if(NNTP::isError($raw)) { // Reset Connection (This happens first time // around since _nntpReset() will perform @@ -1801,7 +1793,7 @@ class SpotNab { do { $msgs = $this->_nntp->getOverview($range, true, false); - if(PEAR::isError($msgs)) + if(NNTP::isError($msgs)) { $this->_nntpReset($group); // Track retry attempts @@ -1816,7 +1808,7 @@ class SpotNab { // Clean up bad results but don't mark fetch as a failure // just report what it found.. (nothing). We do this because - // PEAR::isError() never threw, so the response has to be valid + // NNTP::isError() never threw, so the response has to be valid // even though it's inconsistent if(!$msgs)return array(); if(!is_array($msgs))return array(); @@ -1899,7 +1891,7 @@ class SpotNab { { $message['comments'] = $data['comments']; - $db = new DB(); + $db = new newznab\db\DB(); $sql = sprintf("UPDATE releasecomment " ."SET issynced = 1 WHERE id IN (%s)", implode(",", $data['ids'])); @@ -1964,14 +1956,14 @@ class SpotNab { try { $summary = $this->_nntp->selectGroup($this->_post_group); - if(PEAR::isError($summary)){ + if(NNTP::isError($summary)){ $summary = $this->_nntpReset($this->_post_group); $retries--; continue; } // Check if server will receive an article $_err = $this->_nntp->cmdPost(); - if (PEAR::isError($_err)) { + if (NNTP::isError($_err)) { $summary = $this->_nntpReset($this->_post_group); $retries--; continue; @@ -2000,7 +1992,7 @@ class SpotNab { // right after posting was failing for this group. // $summary = $this->_nntp->selectGroup($this->_post_group); - // if(PEAR::isError($summary)) { + // if(NNTP::isError($summary)) { // $summary = $this->_nntpReset($this->_post_group); // $retries--; // continue; @@ -2064,7 +2056,7 @@ class SpotNab { { // Reselect group if specified $summary = $this->_nntp->selectGroup($this->_post_group); - if(PEAR::isError($summary)) + if(NNTP::isError($summary)) return false; return $summary; } @@ -2253,7 +2245,7 @@ class SpotNab { * but otherwise it's expected format is string "Y-m-d H:i:s" */ - $db = new DB(); + $db = new newznab\db\DB(); // Now we fetch for any new posts since reference point $sql = sprintf("SELECT r.gid, rc.id, rc.text, u.username, " @@ -2496,7 +2488,7 @@ class SpotNab { public function getSources() { - $db = new DB(); + $db = new newznab\db\DB(); return $db->query("SELECT id, lastupdate,lastbroadcast, active, description, " ."(SELECT count(id) from releasecomment where sourceid = s.id)" ." AS comments FROM spotnabsources s"); @@ -2504,14 +2496,14 @@ class SpotNab { public function getSourceById($id) { - $db = new DB(); + $db = new newznab\db\DB(); $sql = sprintf("SELECT * FROM spotnabsources WHERE id = %d", $id); return $db->queryOneRow($sql); } public function addSource($description,$username,$usermail,$usenetgroup,$publickey) { - $db = new DB(); + $db = new newznab\db\DB(); $sql = sprintf("INSERT INTO spotnabsources " ."(description, username, useremail," ." usenetgroup, publickey, active) " @@ -2524,7 +2516,7 @@ class SpotNab { public function updateSource($id, $description,$username,$usermail,$usenetgroup,$publickey) { - $db = new DB(); + $db = new newznab\db\DB(); return $db->queryExec( sprintf("UPDATE spotnabsources SET " ."description = %s, username = %s, useremail = %s," @@ -2536,19 +2528,19 @@ class SpotNab { public function deleteSource($id) { - $db = new DB(); + $db = new newznab\db\DB(); return $db->queryExec(sprintf("DELETE FROM spotnabsources WHERE id = %d", $id)); } public function toggleSource($id, $active) { - $db = new DB(); + $db = new newznab\db\DB(); return $db->queryExec(sprintf("update spotnabsources SET active = %d WHERE id = %d", $active, $id)); } public function getDefaultValue($table,$field) { - $db = new DB(); + $db = new newznab\db\DB(); return $db->query(sprintf("SHOW COLUMNS FROM %s WHERE field = %s", $table, $db->escapeString($field))); } } diff --git a/lib/copy_this/www/lib/thetvdb.php b/lib/copy_this/newznab/controllers/thetvdb.php similarity index 98% rename from lib/copy_this/www/lib/thetvdb.php rename to lib/copy_this/newznab/controllers/thetvdb.php index f2dc048da..899cb1943 100644 --- a/lib/copy_this/www/lib/thetvdb.php +++ b/lib/copy_this/newznab/controllers/thetvdb.php @@ -1,9 +1,7 @@ <?php -require_once(WWW_DIR."/lib/util.php"); -require_once(WWW_DIR."/lib/framework/db.php"); -require_once(WWW_DIR."/lib/postprocess.php"); -require_once(WWW_DIR."/lib/episode.php"); -require_once(WWW_DIR."/lib/category.php"); + +use newznab\db\DB; +use newznab\utility\Utility; class TheTVDB @@ -12,7 +10,7 @@ class TheTVDB const APIKEY = '5F84ECB91B42D719'; /** - * @var DB + * @var newznab\db\DB */ public $pdo; diff --git a/lib/copy_this/www/lib/tvrage.php b/lib/copy_this/newznab/controllers/tvrage.php similarity index 98% rename from lib/copy_this/www/lib/tvrage.php rename to lib/copy_this/newznab/controllers/tvrage.php index 626370df1..4a520a6e7 100644 --- a/lib/copy_this/www/lib/tvrage.php +++ b/lib/copy_this/newznab/controllers/tvrage.php @@ -1,9 +1,8 @@ <?php -require_once(WWW_DIR."/lib/util.php"); -require_once(WWW_DIR."/lib/category.php"); -require_once(WWW_DIR."/lib/nfo.php"); -require_once(WWW_DIR."/lib/framework/db.php"); -require_once(WWW_DIR."/lib/framework/cache.php"); + +use newznab\db\DB; +use newznab\utility\Utility; +use newznab\libraries\Cache; class TvRage { @@ -11,7 +10,7 @@ class TvRage const MATCH_PROBABILITY = 75; /** - * @var DB + * @var newznab\db\DB */ public $pdo; @@ -164,7 +163,7 @@ class TvRage try { - $raw = getURL($this->xmlFullScheduleUrl.$country['country']); + $raw = Utility::getURL($this->xmlFullScheduleUrl.$country['country']); $xml = new SimpleXMLElement($raw); $sched = $xml->xpath('/schedule/DAY'); }catch(Exception $e){ @@ -375,7 +374,7 @@ class TvRage $xml = str_replace('<genre></genre>', '', $xml); $xmlObj = @simplexml_load_string($xml); - $arrXml = objectsIntoArray($xmlObj); + $arrXml = Utility::objectsIntoArray($xmlObj); if (is_array($arrXml)) { @@ -390,7 +389,7 @@ class TvRage public function updateEpInfo($show, $relid) { - $this->pdo = new Db; + $this->pdo = new newznab\db\DB; if (empty($show['airdate']) || !strtotime($show['airdate'])) { $tvairdate = "null"; @@ -430,7 +429,7 @@ class TvRage public function updateRageInfo($rageid, $show, $tvrShow, $relid) { - $this->pdo = new Db; + $this->pdo = new newznab\db\DB; $idCheck = $this->getByRageID($rageid); @@ -631,7 +630,7 @@ class TvRage $xml = str_replace('<genre></genre>', '', $xml); $xmlObj = @simplexml_load_string($xml); - $arrXml = objectsIntoArray($xmlObj); + $arrXml = Utility::objectsIntoArray($xmlObj); if (isset($arrXml['show']) && is_array($arrXml['show'])) { diff --git a/lib/copy_this/www/lib/usermovies.php b/lib/copy_this/newznab/controllers/usermovies.php similarity index 97% rename from lib/copy_this/www/lib/usermovies.php rename to lib/copy_this/newznab/controllers/usermovies.php index d31c1aa1b..7e4d29607 100644 --- a/lib/copy_this/www/lib/usermovies.php +++ b/lib/copy_this/newznab/controllers/usermovies.php @@ -1,5 +1,6 @@ <?php -require_once(WWW_DIR."/lib/framework/db.php"); + +use newznab\db\DB; class UserMovies { diff --git a/lib/copy_this/www/lib/users.php b/lib/copy_this/newznab/controllers/users.php similarity index 98% rename from lib/copy_this/www/lib/users.php rename to lib/copy_this/newznab/controllers/users.php index 55f5071a8..fba4744e3 100644 --- a/lib/copy_this/www/lib/users.php +++ b/lib/copy_this/newznab/controllers/users.php @@ -1,12 +1,7 @@ <?php -require_once(WWW_DIR . "/lib/framework/db.php"); -require_once(WWW_DIR . "/lib/site.php"); -require_once(WWW_DIR . "/lib/releases.php"); -require_once(WWW_DIR . "/lib/forum.php"); -require_once(WWW_DIR . "/lib/util.php"); -require_once(WWW_DIR . "/lib/releasecomments.php"); -require_once(WWW_DIR . "/lib/usermovies.php"); -require_once(WWW_DIR . "/lib/userseries.php"); + +use newznab\db\DB; +use newznab\utility\Utility; class Users { @@ -52,7 +47,7 @@ class Users ]; $options += $defaults; - $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); + $this->pdo = ($options['Settings'] instanceof newznab\db\DB ? $options['Settings'] : new newznab\db\DB()); $this->password_hash_cost = (defined('NN_PASSWORD_HASH_COST') ? NN_PASSWORD_HASH_COST : 11); } @@ -542,8 +537,6 @@ class Users if ($site->registerrecaptcha != 1) return true; - require_once(WWW_DIR . "/lib/recaptchalib.php"); - $resp = recaptcha_check_answer($site->recaptchaprivatekey, $_SERVER["REMOTE_ADDR"], $challenge, $response); return $resp->is_valid; @@ -765,7 +758,6 @@ class Users $ret = array(); if ($data) { - $db = new DB(); $category = new Category(); $data = $category->getByIds($data); foreach ($data as $d) diff --git a/lib/copy_this/www/lib/userseries.php b/lib/copy_this/newznab/controllers/userseries.php similarity index 97% rename from lib/copy_this/www/lib/userseries.php rename to lib/copy_this/newznab/controllers/userseries.php index 16ef8bbf5..012745505 100644 --- a/lib/copy_this/www/lib/userseries.php +++ b/lib/copy_this/newznab/controllers/userseries.php @@ -1,5 +1,6 @@ <?php -require_once(WWW_DIR."/lib/framework/db.php"); + +use newznab\db\DB; class UserSeries { diff --git a/lib/copy_this/www/lib/zipfile.php b/lib/copy_this/newznab/controllers/zipfile.php similarity index 100% rename from lib/copy_this/www/lib/zipfile.php rename to lib/copy_this/newznab/controllers/zipfile.php diff --git a/lib/copy_this/www/lib/framework/db.php b/lib/copy_this/newznab/db/db.php similarity index 98% rename from lib/copy_this/www/lib/framework/db.php rename to lib/copy_this/newznab/db/db.php index d5552bdbe..453f7da4a 100644 --- a/lib/copy_this/www/lib/framework/db.php +++ b/lib/copy_this/newznab/db/db.php @@ -1,9 +1,9 @@ <?php -require_once(WWW_DIR . "lib/framework/cache.php"); -require_once(WWW_DIR . "lib/util.php"); -require_once(WWW_DIR . "lib/ConsoleTools.php"); -require_once(WWW_DIR . "lib/ColorCLI.php"); -require_once(WWW_DIR . "lib/Logger.php"); +namespace newznab\db; + +use \newznab\utility\Utility; +use \newznab\libraries\Cache; +use \newznab\libraries\CacheException; /** @@ -31,7 +31,7 @@ class DB extends \PDO public $ct; /** - * @var ColorCLI Instance variable for logging object. Currently only ColorCLI supported, + * @var \ColorCLI Instance variable for logging object. Currently only ColorCLI supported, * but expanding for full logging with agnostic API planned. */ public $log; @@ -455,7 +455,7 @@ class DB extends \PDO * @param string $query * @param bool $silent Echo or log errors? * - * @return bool|PDOStatement + * @return bool|\PDOStatement */ public function queryExec($query, $silent = false) { @@ -500,7 +500,7 @@ class DB extends \PDO * @param string $query * @param bool $insert * - * @return array|PDOStatement + * @return array|\PDOStatement */ protected function queryExecHelper($query, $insert = false) { @@ -553,7 +553,7 @@ class DB extends \PDO * @param string $query * @param bool $silent Whether to skip echoing errors to the console. * - * @return bool|int|PDOStatement + * @return bool|int|\PDOStatement */ public function exec($query, $silent = false) { @@ -689,7 +689,7 @@ class DB extends \PDO * Fetch a assoc row from a result set * * @param $result - * @return array|PDOStatement + * @return array|\PDOStatement */ public function getAssocArray($result) { @@ -700,7 +700,7 @@ class DB extends \PDO * Get the total number of rows in the result set * * @param $result - * @return int|PDOStatement + * @return int|\PDOStatement */ public function getNumRows($result) { @@ -713,7 +713,7 @@ class DB extends \PDO * @param string $query The query to run. * @param bool $ignore Ignore errors, do not log them? * - * @return bool|PDOStatement + * @return bool|\PDOStatement */ public function queryDirect($query, $ignore = false) { @@ -1052,7 +1052,7 @@ class DB extends \PDO * @param string $query SQL query to run, with optional place holders. * @param array $options Driver options. * - * @return false|PDOstatement on success false on failure. + * @return false|\PDOstatement on success false on failure. * * @link http://www.php.net/pdo.prepare.php */ diff --git a/lib/copy_this/www/populate/AniDB.php b/lib/copy_this/newznab/db/populate/AniDB.php similarity index 98% rename from lib/copy_this/www/populate/AniDB.php rename to lib/copy_this/newznab/db/populate/AniDB.php index c5f3e8686..b28e8752f 100644 --- a/lib/copy_this/www/populate/AniDB.php +++ b/lib/copy_this/newznab/db/populate/AniDB.php @@ -1,7 +1,7 @@ <?php -require_once(WWW_DIR . "/lib/framework/db.php"); -require_once(WWW_DIR . "/lib/releaseimage.php"); -require_once(NN_TMUX . 'lib' . DS . 'simple_html_dom.php'); +require_once NN_LIBS . 'simple_html_dom.php'; + +use newznab\db\DB; class PopulateAniDB @@ -21,7 +21,7 @@ class PopulateAniDB public $imgSavePath; /** - * @var \DB + * @var \newznab\db\DB */ public $pdo; diff --git a/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/Forking.php b/lib/copy_this/newznab/libraries/Forking.php similarity index 98% rename from lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/Forking.php rename to lib/copy_this/newznab/libraries/Forking.php index 07a32513a..c8063c59b 100644 --- a/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/Forking.php +++ b/lib/copy_this/newznab/libraries/Forking.php @@ -1,13 +1,10 @@ <?php -require_once (NN_MULTI . 'forkdaemon-php' . DS . 'fork_daemon.php'); -require_once(NN_LIB . 'framework' .DS . 'db.php'); -require_once(NN_LIB . 'ColorCLI.php'); -require_once(NN_LIB . 'site.php'); -require_once(NN_LIB . 'nntp.php'); -require_once(NN_LIB . 'postprocess.php'); -require_once(NN_LIB . 'nzb.php'); -require_once(NN_LIB . 'RequestID.php'); -require_once(NN_TMUX . 'lib' . DS . 'Pprocess.php'); +namespace newznab\libraries; + +use \newznab\db\DB; +use \newznab\processing\PProcess; + +require_once(NN_LIBS . 'forkdaemon-php' . DS . 'fork_daemon.php'); @@ -19,7 +16,7 @@ require_once(NN_TMUX . 'lib' . DS . 'Pprocess.php'); * For example, you get all the id's of the active groups in the groups table, you then iterate over them and spawn * processes of misc/update_binaries.php passing the group id's. * - * @package nzedb\libraries + * @package newznab\libraries */ class Forking extends \fork_daemon { @@ -95,7 +92,7 @@ class Forking extends \fork_daemon $this->work = []; // Init Settings here, as forking causes errors when it's destroyed. - $this->pdo = new \DB(); + $this->pdo = new DB(); // Process extra work that should not be forked and done before forking. $this->processStartWork(); @@ -881,7 +878,7 @@ class Forking extends \fork_daemon private function processSingle() { $postProcess = new PProcess(['Settings' => $this->pdo, 'ColorCLI' => $this->_colorCLI]); - $pp = new PostProcess(true); + $pp = new \PostProcess(true); //$postProcess->processAnime(); $postProcess->processBooks(); $pp->processBooks(); @@ -1089,7 +1086,7 @@ class Forking extends \fork_daemon private $safeBackfillGroup = ''; /** - * @var \DB + * @var \newznab\db\DB */ public $pdo; diff --git a/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/ForkingImportNZB.php b/lib/copy_this/newznab/libraries/ForkingImportNZB.php similarity index 96% rename from lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/ForkingImportNZB.php rename to lib/copy_this/newznab/libraries/ForkingImportNZB.php index 13f9692e4..74f7119a3 100644 --- a/lib/copy_this/misc/update_scripts/nix_scripts/multiprocessing/ForkingImportNZB.php +++ b/lib/copy_this/newznab/libraries/ForkingImportNZB.php @@ -1,6 +1,7 @@ <?php -require_once(WWW_DIR . "lib/framework/db.php"); -require_once('Forking.php'); +namespace newznab\libraries; + +use newznab\db\DB; /** diff --git a/lib/copy_this/www/lib/framework/cache.php b/lib/copy_this/newznab/libraries/cache.php similarity index 86% rename from lib/copy_this/www/lib/framework/cache.php rename to lib/copy_this/newznab/libraries/cache.php index 344111c6f..d201815c0 100644 --- a/lib/copy_this/www/lib/framework/cache.php +++ b/lib/copy_this/newznab/libraries/cache.php @@ -1,4 +1,7 @@ <?php + +namespace newznab\libraries; + /** * Class Cache * @@ -156,13 +159,13 @@ Class Cache public function __construct() { if (!defined('NN_CACHE_HOSTS')) { - throw new CacheException( + throw new \CacheException( 'The NN_CACHE_HOSTS is not defined! Define it in settings.php' ); } if (!defined('NN_CACHE_TIMEOUT')) { - throw new CacheException( + throw new \CacheException( 'The NN_CACHE_TIMEOUT is not defined! Define it in settings.php, it is the time in seconds to time out from your cache server.' ); } @@ -181,7 +184,7 @@ Class Cache case self::TYPE_REDIS: if (!extension_loaded('redis')) { - throw new CacheException('The redis extension is not loaded!'); + throw new \CacheException('The redis extension is not loaded!'); } $this->server = new Redis(); $this->isRedis = true; @@ -194,9 +197,9 @@ Class Cache case self::TYPE_MEMCACHED: if (!extension_loaded('memcached')) { - throw new CacheException('The memcached extension is not loaded!'); + throw new \CacheException('The memcached extension is not loaded!'); } - $this->server = new Memcached(); + $this->server = new \Memcached(); $this->isRedis = false; if ($this->serializerType !== false) { $this->serializerType = $this->verifySerializer(); @@ -241,14 +244,14 @@ Class Cache $servers = unserialize(NN_CACHE_HOSTS); foreach ($servers as $server) { if ($this->server->connect($server['host'], $server['port'], (float)NN_CACHE_TIMEOUT) === false) { - throw new CacheException('Error connecting to the Redis server!'); + throw new \CacheException('Error connecting to the Redis server!'); } else { $this->connected = true; } } } else { if ($this->server->connect(NN_CACHE_SOCKET_FILE) === false) { - throw new CacheException('Error connecting to the Redis server!'); + throw new \CacheException('Error connecting to the Redis server!'); } else { $this->connected = true; } @@ -256,13 +259,13 @@ Class Cache } else { if ($this->socketFile === false) { if ($this->server->addServers(unserialize(NN_CACHE_HOSTS)) === false) { - throw new CacheException('Error connecting to the Memcached server!'); + throw new \CacheException('Error connecting to the Memcached server!'); } else { $this->connected = true; } } else { if ($this->server->addServers(array(array(NN_CACHE_SOCKET_FILE, 'port' => 0))) === false) { - throw new CacheException('Error connecting to the Memcached server!'); + throw new \CacheException('Error connecting to the Memcached server!'); } else { $this->connected = true; } @@ -300,29 +303,29 @@ Class Cache if (extension_loaded('igbinary')) { $this->IgBinarySupport = true; if ($this->isRedis === true) { - return Redis::SERIALIZER_IGBINARY; + return \Redis::SERIALIZER_IGBINARY; } else { - if (Memcached::HAVE_IGBINARY > 0) { - return Memcached::SERIALIZER_IGBINARY; + if (\Memcached::HAVE_IGBINARY > 0) { + return \Memcached::SERIALIZER_IGBINARY; } else { - throw new CacheException('Error: You have not compiled Memcached with igbinary support!'); + throw new \CacheException('Error: You have not compiled Memcached with igbinary support!'); } } } else { - throw new CacheException('Error: The igbinary extension is not loaded!'); + throw new \CacheException('Error: The igbinary extension is not loaded!'); } case self::SERIALIZER_NONE: if ($this->isRedis === true) { - return Redis::SERIALIZER_NONE; + return \Redis::SERIALIZER_NONE; } else { - throw new CacheException('Error: Disabled serialization is not available on Memcached!'); + throw new \CacheException('Error: Disabled serialization is not available on Memcached!'); } case self::SERIALIZER_PHP: default: if ($this->isRedis === true) { - return Redis::SERIALIZER_PHP; + return \Redis::SERIALIZER_PHP; } else { - return Memcached::SERIALIZER_PHP; + return \Memcached::SERIALIZER_PHP; } } } diff --git a/lib/Pprocess.php b/lib/copy_this/newznab/processing/Pprocess.php similarity index 72% rename from lib/Pprocess.php rename to lib/copy_this/newznab/processing/Pprocess.php index d2a19855a..c373434bf 100644 --- a/lib/Pprocess.php +++ b/lib/copy_this/newznab/processing/Pprocess.php @@ -1,64 +1,34 @@ <?php -require_once(WWW_DIR . "lib/rarinfo/par2info.php"); -require_once(WWW_DIR . "lib/rarinfo/archiveinfo.php"); -require_once(WWW_DIR . "lib/rarinfo/zipinfo.php"); -require_once(WWW_DIR . "lib/framework/db.php"); -require_once(WWW_DIR . "lib/category.php"); -require_once(WWW_DIR . "lib/releases.php"); -require_once(WWW_DIR . "lib/releaseimage.php"); -require_once(WWW_DIR . "lib/releaseextra.php"); -require_once(WWW_DIR . "lib/groups.php"); -require_once(WWW_DIR . 'lib/nntp.php'); -require_once(WWW_DIR . 'lib/music.php'); -require_once(WWW_DIR . 'lib/Musik.php'); -require_once(WWW_DIR . "lib/site.php"); -require_once(WWW_DIR . "lib/Tmux.php"); -require_once(WWW_DIR . "lib/amazon.php"); -require_once(WWW_DIR . "lib/genres.php"); -require_once(WWW_DIR . "lib/anidb.php"); -require_once(WWW_DIR . "lib/book.php"); -require_once(WWW_DIR. "lib/Books.php"); -require_once(WWW_DIR . "lib/Games.php"); -require_once(WWW_DIR . "lib/spotnab.php"); -require_once(WWW_DIR . "lib/thetvdb.php"); -require_once(WWW_DIR . "lib/XXX.php"); -require_once(WWW_DIR . "lib/Logger.php"); -require_once(WWW_DIR . "/lib/ConsoleTools.php"); -require_once(WWW_DIR . "/lib/ColorCLI.php"); -require_once(WWW_DIR . "/processing/post/AniDB.php"); -require_once("nzbcontents.php"); -require_once("namefixer.php"); -require_once("Info.php"); -require_once("prehash.php"); -require_once("Sharing.php"); -require_once("TraktTv.php"); -require_once("Film.php"); -require_once("TvAnger.php"); -require_once("Konsole.php"); -require_once("ProcessAdditional.php"); +namespace newznab\processing; + +use \newznab\db\DB; +use \newznab\processing\post\PostAniDB; +use \newznab\processing\post\ProcessAdditional; + +require_once NN_LIBS . 'rarinfo/par2info.php'; class PProcess { /** - * @var Settings + * @var \newznab\db\DB */ public $pdo; /** * Class instance of debugging. * - * @var Logger + * @var \Logger */ protected $debugging; /** * Instance of NameFixer. - * @var NameFixer + * @var \NameFixer */ protected $nameFixer; /** - * @var Par2Info + * @var \Par2Info */ protected $_par2Info; @@ -81,17 +51,17 @@ class PProcess private $echooutput; /** - * @var Groups + * @var \Groups */ private $groups; /** - * @var Nfo + * @var \Nfo */ private $Nfo; /** - * @var ReleaseFiles + * @var \ReleaseFiles */ private $releaseFiles; @@ -120,12 +90,12 @@ class PProcess $this->site = $s->get(); //\\ Class instances. $this->pdo = (($options['Settings'] instanceof DB) ? $options['Settings'] : new DB()); - $this->groups = (($options['Groups'] instanceof Groups) ? $options['Groups'] : new Groups()); - $this->_par2Info = new Par2Info(); - $this->debugging = ($options['Logger'] instanceof Logger ? $options['Logger'] : new Logger(['ColorCLI' => $this->pdo->log])); - $this->nameFixer = (($options['NameFixer'] instanceof NameFixer) ? $options['NameFixer'] : new NameFixer(['Echo' => $this->echooutput, 'Settings' => $this->pdo, 'Groups' => $this->groups])); - $this->Nfo = (($options['Nfo'] instanceof Info ) ? $options['Nfo'] : new Info(['Echo' => $this->echooutput, 'Settings' => $this->pdo])); - $this->releaseFiles = (($options['ReleaseFiles'] instanceof ReleaseFiles) ? $options['ReleaseFiles'] : new ReleaseFiles($this->pdo)); + $this->groups = (($options['Groups'] instanceof \Groups) ? $options['Groups'] : new \Groups()); + $this->_par2Info = new \Par2Info(); + $this->debugging = ($options['Logger'] instanceof \Logger ? $options['Logger'] : new \Logger(['ColorCLI' => $this->pdo->log])); + $this->nameFixer = (($options['NameFixer'] instanceof \NameFixer) ? $options['NameFixer'] : new \NameFixer(['Echo' => $this->echooutput, 'Settings' => $this->pdo, 'Groups' => $this->groups])); + $this->Nfo = (($options['Nfo'] instanceof \Info ) ? $options['Nfo'] : new \Info(['Echo' => $this->echooutput, 'Settings' => $this->pdo])); + $this->releaseFiles = (($options['ReleaseFiles'] instanceof \ReleaseFiles) ? $options['ReleaseFiles'] : new \ReleaseFiles($this->pdo)); //\\ //\\ Site settings. @@ -166,7 +136,7 @@ class PProcess public function processAnime() { if ($this->site->lookupanidb != 0) { - (new \PostAniDB(['Echo' => $this->echooutput, 'Settings' => $this->pdo]))->processAnimeReleases(); + (new PostAniDB(['Echo' => $this->echooutput, 'Settings' => $this->pdo]))->processAnimeReleases(); } } @@ -202,7 +172,7 @@ class PProcess public function processGames() { if ($this->site->lookupgames != 0) { - (new Games(['Echo' => $this->echooutput, 'Settings' => $this->pdo]))->processGamesReleases(); + (new \Games(['Echo' => $this->echooutput, 'Settings' => $this->pdo]))->processGamesReleases(); } } @@ -220,7 +190,7 @@ class PProcess { $processMovies = (is_numeric($processMovies) ? $processMovies : $this->site->lookupimdb); if ($processMovies > 0) { - (new Film(['Echo' => $this->echooutput, 'Settings' => $this->pdo]))->processMovieReleases($groupID, $guidChar, $processMovies); + (new \Film(['Echo' => $this->echooutput, 'Settings' => $this->pdo]))->processMovieReleases($groupID, $guidChar, $processMovies); } } @@ -239,7 +209,7 @@ class PProcess /** * Process nfo files. * - * @param NNTP $nntp + * @param \NNTP $nntp * @param string $groupID (Optional) id of a group to work on. * @param string $guidChar (Optional) First letter of a release GUID to use to get work. * @@ -257,7 +227,7 @@ class PProcess */ public function processSpotnab() { - $spotnab = new SpotNab(); + $spotnab = new \SpotNab(); $processed = $spotnab->processGID(500); if ($processed > 0) { if ($this->echooutput) { @@ -276,11 +246,11 @@ class PProcess /** * Process comments. * - * @param NNTP $nntp + * @param \NNTP $nntp */ public function processSharing(&$nntp) { - (new Sharing())->start(); + (new \Sharing(['Settings' => $this->pdo, 'NNTP' => $nntp]))->start(); } /** @@ -297,7 +267,7 @@ class PProcess { $processTV = (is_numeric($processTV) ? $processTV : $this->site->lookuptvrage); if ($processTV > 0) { - (new TvAnger(['Echo' => $this->echooutput, 'Settings' => $this->pdo]))->processTvReleases($groupID, $guidChar, $processTV); + (new \TvAnger(['Echo' => $this->echooutput, 'Settings' => $this->pdo]))->processTvReleases($groupID, $guidChar, $processTV); } } @@ -305,7 +275,7 @@ class PProcess { if ($this->site->lookupthetvdb == 1) { - $thetvdb = new TheTVDB($this->echooutput); + $thetvdb = new \TheTVDB($this->echooutput); $thetvdb->processReleases(); } } @@ -316,7 +286,7 @@ class PProcess public function processXXX() { if ($this->site->lookupxxx == 1) { - (new XXX(['Echo' => $this->echooutput, 'Settings' => $this->pdo]))->processXXXReleases(); + (new \XXX(['Echo' => $this->echooutput, 'Settings' => $this->pdo]))->processXXXReleases(); } } @@ -325,7 +295,7 @@ class PProcess * * @note Called externally by tmux/bin/update_per_group and update/postprocess.php * - * @param NNTP $nntp Class NNTP + * @param \NNTP $nntp Class NNTP * @param int|string $groupID (Optional) id of a group to work on. * @param string $guidChar (Optional) First char of release GUID, can be used to select work. * @@ -344,7 +314,7 @@ class PProcess * @param string $messageID MessageID from NZB file. * @param int $relID id of the release. * @param int $groupID Group id of the release. - * @param NNTP $nntp Class NNTP + * @param \NNTP $nntp Class NNTP * @param int $show Only show result or apply iy. * * @return bool @@ -374,15 +344,15 @@ class PProcess if (!in_array( (int)$query['categoryid'], array( - Category::CAT_BOOK_OTHER, - Category::CAT_GAME_OTHER, - Category::CAT_MOVIE_OTHER, - Category::CAT_MUSIC_OTHER, - Category::CAT_PC_MOBILEOTHER, - Category::CAT_TV_OTHER, - Category::CAT_MISC_HASHED, - Category::CAT_XXX_OTHER, - Category::CAT_MISC_OTHER + \Category::CAT_BOOK_OTHER, + \Category::CAT_GAME_OTHER, + \Category::CAT_MOVIE_OTHER, + \Category::CAT_MUSIC_OTHER, + \Category::CAT_PC_MOBILEOTHER, + \Category::CAT_TV_OTHER, + \Category::CAT_MISC_HASHED, + \Category::CAT_XXX_OTHER, + \Category::CAT_MISC_OTHER ) ) ) { diff --git a/lib/copy_this/www/processing/ProcessReleases.php b/lib/copy_this/newznab/processing/ProcessReleases.php similarity index 98% rename from lib/copy_this/www/processing/ProcessReleases.php rename to lib/copy_this/newznab/processing/ProcessReleases.php index 066c20b95..2f1f8e6a6 100644 --- a/lib/copy_this/www/processing/ProcessReleases.php +++ b/lib/copy_this/newznab/processing/ProcessReleases.php @@ -1,18 +1,7 @@ <?php -require_once(NN_LIB . 'framework' . DS . 'db.php'); -require_once(NN_LIB . 'nzb.php'); -require_once(NN_LIB . 'groups.php'); -require_once(NN_LIB . 'ConsoleTools.php'); -require_once(NN_LIB . 'ReleaseCleaning.php'); -require_once(NN_LIB . 'releaseimage.php'); -require_once(NN_LIB . 'releases.php'); -require_once(NN_LIB . 'site.php'); -require_once(NN_LIB . 'RequestIDLocal.php'); -require_once(NN_LIB . 'RequestIDWeb.php'); -require_once(NN_TMUX . 'lib' . DS . 'prehash.php'); -require_once(NN_TMUX . 'lib' . DS . 'Pprocess.php'); - +namespace newznab\processing; +use newznab\db\DB; class ProcessReleases { @@ -69,7 +58,7 @@ class ProcessReleases public $echoCLI; /** - * @var \DB + * @var \newznab\db\DB */ public $pdo; @@ -124,7 +113,7 @@ class ProcessReleases $this->releaseCleaning = ($options['ReleaseCleaning'] instanceof \ReleaseCleaning ? $options['ReleaseCleaning'] : new \ReleaseCleaning($this->pdo)); $this->releases = ($options['Releases'] instanceof \Releases ? $options['Releases'] : new \Releases(['Settings' => $this->pdo, 'Groups' => $this->groups])); $this->releaseImage = ($options['ReleaseImage'] instanceof \ReleaseImage ? $options['ReleaseImage'] : new \ReleaseImage($this->pdo)); - $s = new Sites(); + $s = new \Sites(); $this->site = $s ->get(); $this->tablePerGroup = ($this->site->tablepergroup == 0 ? false : true); diff --git a/lib/copy_this/www/processing/post/AniDB.php b/lib/copy_this/newznab/processing/post/AniDB.php similarity index 95% rename from lib/copy_this/www/processing/post/AniDB.php rename to lib/copy_this/newznab/processing/post/AniDB.php index 8f196f7bf..58a4e11c9 100644 --- a/lib/copy_this/www/processing/post/AniDB.php +++ b/lib/copy_this/newznab/processing/post/AniDB.php @@ -1,11 +1,7 @@ <?php -require_once(WWW_DIR . "/lib/framework/db.php"); -require_once(WWW_DIR . "/lib/category.php"); -require_once(WWW_DIR . "/lib/releaseimage.php"); -require_once(WWW_DIR . "/lib/site.php"); -require_once(WWW_DIR . "/lib/ColorCLI.php"); -require_once(WWW_DIR . "/populate/AniDB.php"); -require_once(WWW_DIR . "/lib/nzb.php"); +namespace newznab\processing\post; + +use newznab\db\DB; class PostAniDB { @@ -25,7 +21,7 @@ class PostAniDB public $padb; /** - * @var DB + * @var newznab\db\DB */ public $pdo; @@ -51,7 +47,7 @@ class PostAniDB $options += $defaults; $this->echooutput = ($options['Echo'] && NN_ECHOCLI); - $this->pdo = ($options['Settings'] instanceof \DB ? $options['Settings'] : new \DB()); + $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); $s = new \Sites(); $this->site = $s->get(); diff --git a/lib/ProcessAdditional.php b/lib/copy_this/newznab/processing/post/ProcessAdditional.php similarity index 95% rename from lib/ProcessAdditional.php rename to lib/copy_this/newznab/processing/post/ProcessAdditional.php index 3095d7330..72778de5f 100644 --- a/lib/ProcessAdditional.php +++ b/lib/copy_this/newznab/processing/post/ProcessAdditional.php @@ -1,35 +1,8 @@ <?php -require_once(WWW_DIR . "/lib/rarinfo/par2info.php"); -require_once(WWW_DIR . "/lib/rarinfo/archiveinfo.php"); -require_once(WWW_DIR . "/lib/rarinfo/zipinfo.php"); -require_once(WWW_DIR . "/lib/framework/db.php"); -require_once(WWW_DIR . "/lib/category.php"); -require_once(WWW_DIR . "/lib/releases.php"); -require_once(WWW_DIR . "/lib/releaseimage.php"); -require_once(WWW_DIR . "/lib/releaseextra.php"); -require_once(WWW_DIR . "/lib/releasefiles.php"); -require_once(WWW_DIR . "/lib/groups.php"); -require_once(WWW_DIR . '/lib/nntp.php'); -require_once(WWW_DIR . "/lib/site.php"); -require_once(WWW_DIR . "/lib/Tmux.php"); -require_once(WWW_DIR . "/lib/amazon.php"); -require_once(WWW_DIR . "/lib/genres.php"); -require_once(WWW_DIR . "/lib/anidb.php"); -require_once(WWW_DIR . "/lib/book.php"); -require_once(WWW_DIR . "/lib/nzb.php"); -require_once(WWW_DIR . "/lib/util.php"); -require_once(WWW_DIR . "/lib/ConsoleTools.php"); -require_once(WWW_DIR . "/lib/ColorCLI.php"); -require_once(WWW_DIR . "/lib/SphinxSearch.php"); -require_once("nzbcontents.php"); -require_once("namefixer.php"); -require_once("Info.php"); -require_once("prehash.php"); -require_once("Sharing.php"); -require_once("TraktTv.php"); -require_once("Film.php"); -require_once("TvAnger.php"); -require_once("Konsole.php"); +namespace newznab\processing\post; + +use newznab\db\DB; +use newznab\utility\Utility; Class ProcessAdditional { @@ -41,7 +14,7 @@ Class ProcessAdditional const maxCompressedFilesToCheck = 20; /** - * @var DB + * @var \newznab\db\DB */ public $pdo; @@ -69,7 +42,7 @@ Class ProcessAdditional protected $_release; /** - * @var NZB + * @var \NZB */ protected $_nzb; @@ -80,17 +53,17 @@ Class ProcessAdditional protected $_nzbContents; /** - * @var Groups + * @var \Groups */ protected $_groups; /** - * @var Par2Info + * @var \Par2Info */ protected $_par2Info; /** - * @var ArchiveInfo + * @var \ArchiveInfo */ protected $_archiveInfo; @@ -180,37 +153,37 @@ Class ProcessAdditional protected $_echoCLI; /** - * @var NNTP + * @var \NNTP */ protected $_nntp; /** - * @var ReleaseFiles + * @var \ReleaseFiles */ protected $_releaseFiles; /** - * @var Categorize + * @var \Categorize */ protected $_categorize; /** - * @var NameFixer + * @var \NameFixer */ protected $_nameFixer; /** - * @var ReleaseExtra + * @var \ReleaseExtra */ protected $_releaseExtra; /** - * @var ReleaseImage + * @var \ReleaseImage */ protected $_releaseImage; /** - * @var Nfo + * @var \Nfo */ protected $_nfo; @@ -308,16 +281,16 @@ Class ProcessAdditional $this->_nzb = ($options['NZB'] instanceof \NZB ? $options['NZB'] : new \NZB($this->pdo)); $this->_groups = ($options['Groups'] instanceof \Groups ? $options['Groups'] : new \Groups(['Settings' => $this->pdo])); - $this->_archiveInfo = new ArchiveInfo(); + $this->_archiveInfo = new \ArchiveInfo(); $this->_releaseFiles = ($options['ReleaseFiles'] instanceof \ReleaseFiles ? $options['ReleaseFiles'] : new \ReleaseFiles($this->pdo)); $this->_categorize = ($options['Categorize'] instanceof \Categorize ? $options['Categorize'] : new \Categorize(['Settings' => $this->pdo])); $this->_nameFixer = ($options['NameFixer'] instanceof \NameFixer ? $options['NameFixer'] : new \NameFixer(['Echo' =>$this->_echoCLI, 'Groups' => $this->_groups, 'Settings' => $this->pdo, 'Categorize' => $this->_categorize])); $this->_releaseExtra = ($options['ReleaseExtra'] instanceof \ReleaseExtra ? $options['ReleaseExtra'] : new \ReleaseExtra($this->pdo)); $this->_releaseImage = ($options['ReleaseImage'] instanceof \ReleaseImage ? $options['ReleaseImage'] : new \ReleaseImage($this->pdo)); - $this->_par2Info = new Par2Info(); + $this->_par2Info = new \Par2Info(); $this->_nfo = ($options['Nfo'] instanceof \Info ? $options['Nfo'] : new \Info(['Echo' => $this->_echoCLI, 'Settings' => $this->pdo])); $this->sphinx = ($options['SphinxSearch'] instanceof \SphinxSearch ? $options['SphinxSearch'] : new \SphinxSearch()); - $s = new Sites(); + $s = new \Sites(); $this->site = $s->get(); $this->_innerFileBlacklist = ($this->site->innerfileblacklist == '' ? false : $this->site->innerfileblacklist); @@ -330,11 +303,11 @@ Class ProcessAdditional // Pass the binary extractors to ArchiveInfo. $clients = array(); if ($this->site->unrarpath != '') { - $clients += array(ArchiveInfo::TYPE_RAR => $this->site->unrarpath); + $clients += array(\ArchiveInfo::TYPE_RAR => $this->site->unrarpath); $this->_unrarPath = $this->site->unrarpath; } if ($this->site->zippath != '') { - $clients += array(ArchiveInfo::TYPE_ZIP => $this->site->zippath); + $clients += array(\ArchiveInfo::TYPE_ZIP => $this->site->zippath); $this->_7zipPath = $this->site->zippath; } $this->_archiveInfo->setExternalClients($clients); @@ -481,7 +454,7 @@ Class ProcessAdditional } if (!is_dir($this->_mainTmpPath)) { - throw new ProcessAdditionalException('Could create the tmpunrar folder (' . $this->_mainTmpPath . ')'); + throw new \ProcessAdditionalException('Could create the tmpunrar folder (' . $this->_mainTmpPath . ')'); } $this->_clearMainTmpPath(); @@ -956,12 +929,12 @@ Class ProcessAdditional if (!empty($this->_archiveInfo->isEncrypted) || (isset($dataSummary['is_encrypted']) && $dataSummary['is_encrypted'] != 0)) { $this->_debug('ArchiveInfo: Compressed file has a password.'); $this->_releaseHasPassword = true; - $this->_passwordStatus[] = Releases::PASSWD_RAR; + $this->_passwordStatus[] = \Releases::PASSWD_RAR; return false; } switch ($dataSummary['main_type']) { - case ArchiveInfo::TYPE_RAR: + case \ArchiveInfo::TYPE_RAR: if ($this->_echoCLI) { $this->_echo('r', 'primaryOver', false); } @@ -969,7 +942,7 @@ Class ProcessAdditional if ($this->_extractUsingRarInfo === false && $this->_unrarPath !== false) { $fileName = $this->tmpPath . uniqid() . '.rar'; file_put_contents($fileName, $compressedData); - runCmd( + Utility::runCmd( $this->_killString . $this->_unrarPath . '" e -ai -ep -c- -id -inul -kb -or -p- -r -y "' . $fileName . '" "' . $this->tmpPath . 'unrar/"' @@ -977,7 +950,7 @@ Class ProcessAdditional unlink($fileName); } break; - case ArchiveInfo::TYPE_ZIP: + case \ArchiveInfo::TYPE_ZIP: if ($this->_echoCLI) { $this->_echo('z', 'primaryOver', false); } @@ -985,7 +958,7 @@ Class ProcessAdditional if ($this->_extractUsingRarInfo === false && $this->_7zipPath !== false) { $fileName = $this->tmpPath . uniqid() . '.zip'; file_put_contents($fileName, $compressedData); - runCmd( + Utility::runCmd( $this->_killString . $this->_7zipPath . '" x "' . $fileName . '" -bd -y -o"' . $this->tmpPath . 'unzip/"' ); @@ -1028,13 +1001,13 @@ Class ProcessAdditional if ($file['pass'] == true) { $this->_releaseHasPassword = true; - $this->_passwordStatus[] = Releases::PASSWD_RAR; + $this->_passwordStatus[] = \Releases::PASSWD_RAR; break; } if ($this->_innerFileBlacklist !== false && preg_match($this->_innerFileBlacklist, $file['name'])) { $this->_releaseHasPassword = true; - $this->_passwordStatus[] = Releases::PASSWD_POTENTIAL; + $this->_passwordStatus[] = \Releases::PASSWD_POTENTIAL; break; } @@ -1111,7 +1084,7 @@ Class ProcessAdditional ) { $this->_debug('Codec spam found, setting release to potentially passworded.' . PHP_EOL); $this->_releaseHasPassword = true; - $this->_passwordStatus[] = Releases::PASSWD_POTENTIAL; + $this->_passwordStatus[] = \Releases::PASSWD_POTENTIAL; } //Run a PreDB filename check on insert to try and match the release else if (strpos($file['name'], '.') != 0 && strlen($file['name']) > 0) { $this->_release['filename'] = $file['name']; @@ -1143,7 +1116,7 @@ Class ProcessAdditional // Get all the compressed files in the temp folder. $files = $this->_getTempDirectoryContents('/.*\.([rz]\d{2,}|rar|zipx?|0{0,2}1)($|[^a-z0-9])/i'); - if ($files instanceof Traversable) { + if ($files instanceof \Traversable) { foreach ($files as $file) { // Check if the file exists. @@ -1170,7 +1143,7 @@ Class ProcessAdditional // Get all the remaining files in the temp dir. $files = $this->_getTempDirectoryContents(); - if ($files instanceof Traversable) { + if ($files instanceof \Traversable) { foreach ($files as $file) { $file = (string)$file; @@ -1549,7 +1522,7 @@ Class ProcessAdditional UPDATE releases SET passwordstatus = %d, rarinnerfilecount = %d %s %s %s WHERE id = %d', - ($this->_processPasswords === true ? $this->_passwordStatus : Releases::PASSWD_NONE), + ($this->_processPasswords === true ? $this->_passwordStatus : \Releases::PASSWD_NONE), $releaseFiles['count'], $iSQL, $vSQL, @@ -1577,19 +1550,19 @@ Class ProcessAdditional } try { if ($pattern !== '') { - return new RegexIterator( - new RecursiveIteratorIterator( - new RecursiveDirectoryIterator($path) + return new \RegexIterator( + new \RecursiveIteratorIterator( + new \RecursiveDirectoryIterator($path) ), $pattern, - RecursiveRegexIterator::GET_MATCH + \RecursiveRegexIterator::GET_MATCH ); } else { - return new RecursiveIteratorIterator( - new RecursiveDirectoryIterator($path) + return new \RecursiveIteratorIterator( + new \RecursiveDirectoryIterator($path) ); } - } catch (exception $e) { + } catch (\exception $e) { $this->_debug('ERROR: Could not open temp dir: ' . $e->getMessage() . PHP_EOL); return false; } @@ -1626,14 +1599,14 @@ Class ProcessAdditional ) ); - $musicParent = (string)Category::CAT_PARENT_MUSIC; + $musicParent = (string)\Category::CAT_PARENT_MUSIC; if ($rQuery === false || !preg_match( sprintf( '/%d\d{3}|%d|%d|%d/', $musicParent[0], - Category::CAT_MISC_OTHER, - Category::CAT_MOVIE_OTHER, - Category::CAT_TV_OTHER + \Category::CAT_MISC_OTHER, + \Category::CAT_MOVIE_OTHER, + \Category::CAT_TV_OTHER ), $rQuery['id'] ) @@ -1647,13 +1620,13 @@ Class ProcessAdditional if ($retVal === false) { // Get the media info for the file. - $xmlArray = runCmd( + $xmlArray = Utility::runCmd( $this->_killString . $this->site->mediainfopath . '" --Output=XML "' . $fileLocation . '"' ); if (is_array($xmlArray)) { // Convert to array. - $arrXml = objectsIntoArray(@simplexml_load_string(implode("\n", $xmlArray))); + $arrXml = Utility::objectsIntoArray(@simplexml_load_string(implode("\n", $xmlArray))); if (isset($arrXml['File']['track'])) { @@ -1674,9 +1647,9 @@ Class ProcessAdditional // Get the category or try to determine it. if ($ext === 'MP3') { - $newCat = Category::CAT_MUSIC_MP3; + $newCat = \Category::CAT_MUSIC_MP3; } else if ($ext === 'FLAC') { - $newCat = Category::CAT_MUSIC_LOSSLESS; + $newCat = \Category::CAT_MUSIC_LOSSLESS; } else { $newCat = $this->_categorize->determineCategory($rQuery['groupid'],$newName); } @@ -1698,7 +1671,7 @@ Class ProcessAdditional // Echo the changed name. if ($this->_echoCLI) { - NameFixer::echoChangedReleaseName( + \NameFixer::echoChangedReleaseName( array( 'new_name' => $newName, 'old_name' => $rQuery['searchname'], @@ -1734,7 +1707,7 @@ Class ProcessAdditional $audioFileName = ($this->_release['guid'] . '.ogg'); // Create an audio sample. - runCmd( + Utility::runCmd( $this->_killString . $this->site->ffmpegpath . '" -t 30 -i "' . @@ -1837,7 +1810,7 @@ Class ProcessAdditional $tmpVideo = ($this->tmpPath . uniqid() . $extension); // Get the real duration of the file. - $time = runCmd( + $time = Utility::runCmd( $this->_killString . $this->site->ffmpegpath . '" -i "' . $videoLocation . @@ -1883,7 +1856,7 @@ Class ProcessAdditional $time = $this->getVideoTime($fileLocation); // Create the image. - runCmd( + Utility::runCmd( $this->_killString . $this->site->ffmpegpath . '" -i "' . @@ -1974,7 +1947,7 @@ Class ProcessAdditional } // Try to get the sample (from the end instead of the start). - runCmd( + Utility::runCmd( $this->_killString . $this->site->ffmpegpath . '" -i "' . @@ -1991,7 +1964,7 @@ Class ProcessAdditional if ($newMethod === false) { // If longer than 60 or we could not get the video length, run the old way. - runCmd( + Utility::runCmd( $this->_killString . $this->site->ffmpegpath . '" -i "' . @@ -2066,7 +2039,7 @@ Class ProcessAdditional if (is_file($fileLocation)) { // Run media info on it. - $xmlArray =runCmd( + $xmlArray = Utility::runCmd( $this->_killString . $this->site->mediainfopath . '" --Output=XML "' . $fileLocation . '"' ); @@ -2127,15 +2100,15 @@ Class ProcessAdditional in_array( ((int)$this->_release['categoryid']), array( - Category::CAT_BOOK_OTHER, - Category::CAT_GAME_OTHER, - Category::CAT_MOVIE_OTHER, - Category::CAT_MUSIC_OTHER, - Category::CAT_PC_MOBILEOTHER, - Category::CAT_TV_OTHER, - Category::CAT_MISC_HASHED, - Category::CAT_XXX_OTHER, - Category::CAT_MISC_OTHER + \Category::CAT_BOOK_OTHER, + \Category::CAT_GAME_OTHER, + \Category::CAT_MOVIE_OTHER, + \Category::CAT_MUSIC_OTHER, + \Category::CAT_PC_MOBILEOTHER, + \Category::CAT_TV_OTHER, + \Category::CAT_MISC_HASHED, + \Category::CAT_XXX_OTHER, + \Category::CAT_MISC_OTHER ) ) ) { @@ -2286,7 +2259,7 @@ Class ProcessAdditional // Echo the changed name to CLI. if ($this->_echoCLI) { - NameFixer::echoChangedReleaseName( + \NameFixer::echoChangedReleaseName( array( 'new_name' => $newName, 'old_name' => $this->_release['searchname'], diff --git a/lib/copy_this/www/lib/SmartyUtils.php b/lib/copy_this/newznab/utility/SmartyUtils.php similarity index 100% rename from lib/copy_this/www/lib/SmartyUtils.php rename to lib/copy_this/newznab/utility/SmartyUtils.php diff --git a/lib/copy_this/www/lib/util.php b/lib/copy_this/newznab/utility/Utility.php similarity index 60% rename from lib/copy_this/www/lib/util.php rename to lib/copy_this/newznab/utility/Utility.php index f57880a1d..9ec5f2d21 100644 --- a/lib/copy_this/www/lib/util.php +++ b/lib/copy_this/newznab/utility/Utility.php @@ -1,6 +1,6 @@ <?php -require_once(WWW_DIR."/lib/site.php"); -require_once(NN_TMUX . 'lib' . DS . 'PHPMailer' . DS . 'class.phpmailer.php'); +namespace newznab\utility; + /* * General util functions. @@ -15,10 +15,8 @@ class Utility static public function clearScreen() { - if (self::isCLI()) - { - if (self::isWin()) - { + if (self::isCLI()) { + if (self::isWin()) { passthru('cls'); } else { passthru('clear'); @@ -245,6 +243,7 @@ class Utility } gzclose($gzFile); } + return ($string === '' ? false : $string); } @@ -304,6 +303,7 @@ class Utility CURLOPT_SSL_VERIFYHOST => 0, ]; } + return $options; } @@ -322,7 +322,7 @@ class Utility 'url' => '', // The URL to download. 'method' => 'get', // Http method, get/post/etc.. 'postdata' => '', // Data to send on post method. - 'enctype' => '', // Encoding type + 'enctype' => '', // Encoding type 'language' => '', // Language in header string. 'debug' => false, // Show curl debug information. 'useragent' => '', // User agent string. @@ -384,7 +384,7 @@ class Utility ]; } if ($options['enctype'] !== '') { - $context += [CURLOPT_ENCODING => $options['enctype']]; + $context += [CURLOPT_ENCODING => $options['enctype']]; } if ($options['debug']) { $context += [ @@ -397,7 +397,7 @@ class Utility curl_setopt_array($ch, $context); $buffer = curl_exec($ch); - $err = curl_errno($ch); + $err = curl_errno($ch); curl_close($ch); if ($err !== 0) { @@ -429,16 +429,18 @@ class Utility public static function getCoverURL(array $options = []) { $defaults = [ - 'id' => null, + 'id' => null, 'suffix' => '-cover.jpg', - 'type' => '', + 'type' => '', ]; $options += $defaults; $fileSpecTemplate = '%s/%s%s'; $fileSpec = ''; if (!empty($options['id']) && in_array($options['type'], - ['anime', 'audio', 'audiosample', 'book', 'console', 'games', 'movies', 'music', 'preview', 'sample', 'tvrage', 'video', 'xxx'])) { + ['anime', 'audio', 'audiosample', 'book', 'console', 'games', 'movies', 'music', 'preview', 'sample', 'tvrage', 'video', 'xxx'] + ) + ) { $fileSpec = sprintf($fileSpecTemplate, $options['type'], $options['id'], $options['suffix']); $fileSpec = file_exists(NN_COVERS . $fileSpec) ? $fileSpec : sprintf($fileSpecTemplate, $options['type'], 'no', $options['suffix']); @@ -463,7 +465,7 @@ class Utility // If the mailer couldn't instantiate there's a good chance the user has an incomplete update & we should fallback to php mail() // @todo Log this failure. - if (!defined('PHPMAILER_ENABLED') || PHPMAILER_ENABLED !== true || !($mail instanceof PHPMailer)) { + if (!defined('PHPMAILER_ENABLED') || PHPMAILER_ENABLED !== true || !($mail instanceof \PHPMailer)) { $headers = 'From: ' . $from . $eol; $headers .= 'Reply-To: ' . $from . $eol; $headers .= 'Return-Path: ' . $from . $eol; @@ -486,8 +488,7 @@ class Utility } // If the user enabled SMTP & Auth but did not setup credentials, throw an exception. - if (defined('PHPMAILER_SMTP_AUTH') && PHPMAILER_SMTP_AUTH == true) - { + if (defined('PHPMAILER_SMTP_AUTH') && PHPMAILER_SMTP_AUTH == true) { if ((!defined('PHPMAILER_SMTP_USER') || PHPMAILER_SMTP_USER === '') || (!defined('PHPMAILER_SMTP_PASSWORD') || PHPMAILER_SMTP_PASSWORD === '') ) { @@ -515,16 +516,16 @@ class Utility $mail->Password = PHPMAILER_SMTP_PASSWORD; } } - $s = new Sites(); + $s = new \Sites(); $settings = $s->get(); $site_email = $settings->email; $fromEmail = (PHPMAILER_FROM_EMAIL === '') ? $site_email : PHPMAILER_FROM_EMAIL; - $fromName = (PHPMAILER_FROM_NAME === '') ? $settings->title : PHPMAILER_FROM_NAME; - $replyTo = (PHPMAILER_REPLYTO === '') ? $site_email : PHPMAILER_REPLYTO; + $fromName = (PHPMAILER_FROM_NAME === '') ? $settings->title : PHPMAILER_FROM_NAME; + $replyTo = (PHPMAILER_REPLYTO === '') ? $site_email : PHPMAILER_REPLYTO; - (PHPMAILER_BCC !== '') ? $mail->addBCC(PHPMAILER_BCC) : null; + (PHPMAILER_BCC !== '') ? $mail->addBCC(PHPMAILER_BCC) : null; $mail->setFrom($fromEmail, $fromName); $mail->addAddress($to); @@ -554,10 +555,10 @@ class Utility static public function fileInfo($path) { $output = ''; - $magicPath = (new Sites())->get()->magic_file_path; + $magicPath = (new \Sites())->get()->magic_file_path; if (self::hasCommand('file') && (!self::isWin() || !empty($magicPath))) { $magicSwitch = empty($magicPath) ? '' : " -m $magicPath"; - $output = runCmd('file' . $magicSwitch . ' -b "' . $path . '"'); + $output = Utility::runCmd('file' . $magicSwitch . ' -b "' . $path . '"'); if (is_array($output)) { switch (count($output)) { @@ -575,7 +576,7 @@ class Utility $output = ''; } } else { - $fileInfo = empty($magicPath) ? new finfo(FILEINFO_RAW) : new finfo(FILEINFO_RAW, $magicPath); + $fileInfo = empty($magicPath) ? new \finfo(FILEINFO_RAW) : new \finfo(FILEINFO_RAW, $magicPath); $output = $fileInfo->file($path); if (empty($output)) { @@ -587,548 +588,554 @@ class Utility return $output; } -} -function checkStatus ($code) -{ - return ($code == 0) ? true : false; -} - -/** - * Convert Code page 437 chars to UTF. - * - * @param string $str - * - * @return string - */ -function cp437toUTF ($str) -{ - $out = ''; - for ($i = 0; $i < strlen($str); $i++) { - $ch = ord($str{$i}); - switch ($ch) { - case 128: - $out .= 'Ç'; - break; - case 129: - $out .= 'ü'; - break; - case 130: - $out .= 'é'; - break; - case 131: - $out .= 'â'; - break; - case 132: - $out .= 'ä'; - break; - case 133: - $out .= 'à'; - break; - case 134: - $out .= 'Ã¥'; - break; - case 135: - $out .= 'ç'; - break; - case 136: - $out .= 'ê'; - break; - case 137: - $out .= 'ë'; - break; - case 138: - $out .= 'è'; - break; - case 139: - $out .= 'ï'; - break; - case 140: - $out .= 'î'; - break; - case 141: - $out .= 'ì'; - break; - case 142: - $out .= 'Ä'; - break; - case 143: - $out .= 'Ã…'; - break; - case 144: - $out .= 'É'; - break; - case 145: - $out .= 'æ'; - break; - case 146: - $out .= 'Æ'; - break; - case 147: - $out .= 'ô'; - break; - case 148: - $out .= 'ö'; - break; - case 149: - $out .= 'ò'; - break; - case 150: - $out .= 'û'; - break; - case 151: - $out .= 'ù'; - break; - case 152: - $out .= 'ÿ'; - break; - case 153: - $out .= 'Ö'; - break; - case 154: - $out .= 'Ü'; - break; - case 155: - $out .= '¢'; - break; - case 156: - $out .= '£'; - break; - case 157: - $out .= 'Â¥'; - break; - case 158: - $out .= 'â‚§'; - break; - case 159: - $out .= 'Æ’'; - break; - case 160: - $out .= 'á'; - break; - case 161: - $out .= 'í'; - break; - case 162: - $out .= 'ó'; - break; - case 163: - $out .= 'ú'; - break; - case 164: - $out .= 'ñ'; - break; - case 165: - $out .= 'Ñ'; - break; - case 166: - $out .= 'ª'; - break; - case 167: - $out .= 'º'; - break; - case 168: - $out .= '¿'; - break; - case 169: - $out .= 'âŒ'; - break; - case 170: - $out .= '¬'; - break; - case 171: - $out .= '½'; - break; - case 172: - $out .= '¼'; - break; - case 173: - $out .= '¡'; - break; - case 174: - $out .= '«'; - break; - case 175: - $out .= '»'; - break; - case 176: - $out .= 'â–‘'; - break; - case 177: - $out .= 'â–’'; - break; - case 178: - $out .= 'â–“'; - break; - case 179: - $out .= '│'; - break; - case 180: - $out .= '┤'; - break; - case 181: - $out .= 'â•¡'; - break; - case 182: - $out .= 'â•¢'; - break; - case 183: - $out .= 'â•–'; - break; - case 184: - $out .= 'â••'; - break; - case 185: - $out .= 'â•£'; - break; - case 186: - $out .= 'â•‘'; - break; - case 187: - $out .= 'â•—'; - break; - case 188: - $out .= 'â•'; - break; - case 189: - $out .= '╜'; - break; - case 190: - $out .= 'â•›'; - break; - case 191: - $out .= 'â”'; - break; - case 192: - $out .= 'â””'; - break; - case 193: - $out .= 'â”´'; - break; - case 194: - $out .= '┬'; - break; - case 195: - $out .= '├'; - break; - case 196: - $out .= '─'; - break; - case 197: - $out .= '┼'; - break; - case 198: - $out .= '╞'; - break; - case 199: - $out .= '╟'; - break; - case 200: - $out .= '╚'; - break; - case 201: - $out .= 'â•”'; - break; - case 202: - $out .= 'â•©'; - break; - case 203: - $out .= '╦'; - break; - case 204: - $out .= 'â• '; - break; - case 205: - $out .= 'â•'; - break; - case 206: - $out .= '╬'; - break; - case 207: - $out .= 'â•§'; - break; - case 208: - $out .= '╨'; - break; - case 209: - $out .= '╤'; - break; - case 210: - $out .= 'â•¥'; - break; - case 211: - $out .= 'â•™'; - break; - case 212: - $out .= '╘'; - break; - case 213: - $out .= 'â•’'; - break; - case 214: - $out .= 'â•“'; - break; - case 215: - $out .= 'â•«'; - break; - case 216: - $out .= '╪'; - break; - case 217: - $out .= '┘'; - break; - case 218: - $out .= '┌'; - break; - case 219: - $out .= 'â–ˆ'; - break; - case 220: - $out .= 'â–„'; - break; - case 221: - $out .= 'â–Œ'; - break; - case 222: - $out .= 'â–'; - break; - case 223: - $out .= 'â–€'; - break; - case 224: - $out .= 'α'; - break; - case 225: - $out .= 'ß'; - break; - case 226: - $out .= 'Γ'; - break; - case 227: - $out .= 'Ï€'; - break; - case 228: - $out .= 'Σ'; - break; - case 229: - $out .= 'σ'; - break; - case 230: - $out .= 'µ'; - break; - case 231: - $out .= 'Ï„'; - break; - case 232: - $out .= 'Φ'; - break; - case 233: - $out .= 'Θ'; - break; - case 234: - $out .= 'Ω'; - break; - case 235: - $out .= 'δ'; - break; - case 236: - $out .= '∞'; - break; - case 237: - $out .= 'φ'; - break; - case 238: - $out .= 'ε'; - break; - case 239: - $out .= '∩'; - break; - case 240: - $out .= '≡'; - break; - case 241: - $out .= '±'; - break; - case 242: - $out .= '≥'; - break; - case 243: - $out .= '≤'; - break; - case 244: - $out .= '⌠'; - break; - case 245: - $out .= '⌡'; - break; - case 246: - $out .= '÷'; - break; - case 247: - $out .= '≈'; - break; - case 248: - $out .= '°'; - break; - case 249: - $out .= '∙'; - break; - case 250: - $out .= '·'; - break; - case 251: - $out .= '√'; - break; - case 252: - $out .= 'â¿'; - break; - case 253: - $out .= '²'; - break; - case 254: - $out .= 'â– '; - break; - case 255: - $out .= ' '; - break; - default : - $out .= chr($ch); - } + public function checkStatus($code) + { + return ($code == 0) ? true : false; } - return $out; -} -/** - * Fetches an embeddable video to a IMDB trailer from http://www.traileraddict.com - * - * @param $imdbID - * - * @return string - */ -function imdb_trailers($imdbID) -{ - $xml = Utility::getUrl(['http://api.traileraddict.com/?imdb=' . $imdbID]); - if ($xml !== false) { - if (preg_match('/(<iframe.+?<\/iframe>)/i', $xml, $html)) { - return $html[1]; + /** + * Convert Code page 437 chars to UTF. + * + * @param string $str + * + * @return string + */ + public static function cp437toUTF($str) + { + $out = ''; + for ($i = 0; $i < strlen($str); $i++) { + $ch = ord($str{$i}); + switch ($ch) { + case 128: + $out .= 'Ç'; + break; + case 129: + $out .= 'ü'; + break; + case 130: + $out .= 'é'; + break; + case 131: + $out .= 'â'; + break; + case 132: + $out .= 'ä'; + break; + case 133: + $out .= 'à'; + break; + case 134: + $out .= 'Ã¥'; + break; + case 135: + $out .= 'ç'; + break; + case 136: + $out .= 'ê'; + break; + case 137: + $out .= 'ë'; + break; + case 138: + $out .= 'è'; + break; + case 139: + $out .= 'ï'; + break; + case 140: + $out .= 'î'; + break; + case 141: + $out .= 'ì'; + break; + case 142: + $out .= 'Ä'; + break; + case 143: + $out .= 'Ã…'; + break; + case 144: + $out .= 'É'; + break; + case 145: + $out .= 'æ'; + break; + case 146: + $out .= 'Æ'; + break; + case 147: + $out .= 'ô'; + break; + case 148: + $out .= 'ö'; + break; + case 149: + $out .= 'ò'; + break; + case 150: + $out .= 'û'; + break; + case 151: + $out .= 'ù'; + break; + case 152: + $out .= 'ÿ'; + break; + case 153: + $out .= 'Ö'; + break; + case 154: + $out .= 'Ü'; + break; + case 155: + $out .= '¢'; + break; + case 156: + $out .= '£'; + break; + case 157: + $out .= 'Â¥'; + break; + case 158: + $out .= 'â‚§'; + break; + case 159: + $out .= 'Æ’'; + break; + case 160: + $out .= 'á'; + break; + case 161: + $out .= 'í'; + break; + case 162: + $out .= 'ó'; + break; + case 163: + $out .= 'ú'; + break; + case 164: + $out .= 'ñ'; + break; + case 165: + $out .= 'Ñ'; + break; + case 166: + $out .= 'ª'; + break; + case 167: + $out .= 'º'; + break; + case 168: + $out .= '¿'; + break; + case 169: + $out .= 'âŒ'; + break; + case 170: + $out .= '¬'; + break; + case 171: + $out .= '½'; + break; + case 172: + $out .= '¼'; + break; + case 173: + $out .= '¡'; + break; + case 174: + $out .= '«'; + break; + case 175: + $out .= '»'; + break; + case 176: + $out .= 'â–‘'; + break; + case 177: + $out .= 'â–’'; + break; + case 178: + $out .= 'â–“'; + break; + case 179: + $out .= '│'; + break; + case 180: + $out .= '┤'; + break; + case 181: + $out .= 'â•¡'; + break; + case 182: + $out .= 'â•¢'; + break; + case 183: + $out .= 'â•–'; + break; + case 184: + $out .= 'â••'; + break; + case 185: + $out .= 'â•£'; + break; + case 186: + $out .= 'â•‘'; + break; + case 187: + $out .= 'â•—'; + break; + case 188: + $out .= 'â•'; + break; + case 189: + $out .= '╜'; + break; + case 190: + $out .= 'â•›'; + break; + case 191: + $out .= 'â”'; + break; + case 192: + $out .= 'â””'; + break; + case 193: + $out .= 'â”´'; + break; + case 194: + $out .= '┬'; + break; + case 195: + $out .= '├'; + break; + case 196: + $out .= '─'; + break; + case 197: + $out .= '┼'; + break; + case 198: + $out .= '╞'; + break; + case 199: + $out .= '╟'; + break; + case 200: + $out .= '╚'; + break; + case 201: + $out .= 'â•”'; + break; + case 202: + $out .= 'â•©'; + break; + case 203: + $out .= '╦'; + break; + case 204: + $out .= 'â• '; + break; + case 205: + $out .= 'â•'; + break; + case 206: + $out .= '╬'; + break; + case 207: + $out .= 'â•§'; + break; + case 208: + $out .= '╨'; + break; + case 209: + $out .= '╤'; + break; + case 210: + $out .= 'â•¥'; + break; + case 211: + $out .= 'â•™'; + break; + case 212: + $out .= '╘'; + break; + case 213: + $out .= 'â•’'; + break; + case 214: + $out .= 'â•“'; + break; + case 215: + $out .= 'â•«'; + break; + case 216: + $out .= '╪'; + break; + case 217: + $out .= '┘'; + break; + case 218: + $out .= '┌'; + break; + case 219: + $out .= 'â–ˆ'; + break; + case 220: + $out .= 'â–„'; + break; + case 221: + $out .= 'â–Œ'; + break; + case 222: + $out .= 'â–'; + break; + case 223: + $out .= 'â–€'; + break; + case 224: + $out .= 'α'; + break; + case 225: + $out .= 'ß'; + break; + case 226: + $out .= 'Γ'; + break; + case 227: + $out .= 'Ï€'; + break; + case 228: + $out .= 'Σ'; + break; + case 229: + $out .= 'σ'; + break; + case 230: + $out .= 'µ'; + break; + case 231: + $out .= 'Ï„'; + break; + case 232: + $out .= 'Φ'; + break; + case 233: + $out .= 'Θ'; + break; + case 234: + $out .= 'Ω'; + break; + case 235: + $out .= 'δ'; + break; + case 236: + $out .= '∞'; + break; + case 237: + $out .= 'φ'; + break; + case 238: + $out .= 'ε'; + break; + case 239: + $out .= '∩'; + break; + case 240: + $out .= '≡'; + break; + case 241: + $out .= '±'; + break; + case 242: + $out .= '≥'; + break; + case 243: + $out .= '≤'; + break; + case 244: + $out .= '⌠'; + break; + case 245: + $out .= '⌡'; + break; + case 246: + $out .= '÷'; + break; + case 247: + $out .= '≈'; + break; + case 248: + $out .= '°'; + break; + case 249: + $out .= '∙'; + break; + case 250: + $out .= '·'; + break; + case 251: + $out .= '√'; + break; + case 252: + $out .= 'â¿'; + break; + case 253: + $out .= '²'; + break; + case 254: + $out .= 'â– '; + break; + case 255: + $out .= ' '; + break; + default : + $out .= chr($ch); + } } + + return $out; + } + + /** + * Fetches an embeddable video to a IMDB trailer from http://www.traileraddict.com + * + * @param $imdbID + * + * @return string + */ + public static function imdb_trailers($imdbID) + { + $xml = Utility::getUrl(['http://api.traileraddict.com/?imdb=' . $imdbID]); + if ($xml !== false) { + if (preg_match('/(<iframe.+?<\/iframe>)/i', $xml, $html)) { + return $html[1]; + } + } + + return ''; } - return ''; -} // Check if O/S is windows. -function isWindows () -{ - return Utility::isWin(); -} + public static function isWindows() + { + return Utility::isWin(); + } // Convert obj to array. -function objectsIntoArray ($arrObjData, $arrSkipIndices = []) -{ - $arrData = []; + public function objectsIntoArray($arrObjData, $arrSkipIndices = []) + { + $arrData = []; - // If input is object, convert into array. - if (is_object($arrObjData)) { - $arrObjData = get_object_vars($arrObjData); - } - - if (is_array($arrObjData)) { - foreach ($arrObjData as $index => $value) { - // Recursive call. - if (is_object($value) || is_array($value)) { - $value = objectsIntoArray($value, $arrSkipIndices); - } - if (in_array($index, $arrSkipIndices)) { - continue; - } - $arrData[$index] = $value; + // If input is object, convert into array. + if (is_object($arrObjData)) { + $arrObjData = get_object_vars($arrObjData); } - } - return $arrData; -} -/** - * Run CLI command. - * - * @param string $command - * @param bool $debug - * - * @return array - */ -function runCmd ($command, $debug = false) -{ - $nl = PHP_EOL; - if (isWindows() && strpos(phpversion(), "5.2") !== false) { - $command = "\"" . $command . "\""; + if (is_array($arrObjData)) { + foreach ($arrObjData as $index => $value) { + // Recursive call. + if (is_object($value) || is_array($value)) { + $value = Utility::objectsIntoArray($value, $arrSkipIndices); + } + if (in_array($index, $arrSkipIndices)) { + continue; + } + $arrData[$index] = $value; + } + } + + return $arrData; } - if ($debug) { - echo '-Running Command: ' . $nl . ' ' . $command . $nl; + /** + * Run CLI command. + * + * @param string $command + * @param bool $debug + * + * @return array + */ + public function runCmd($command, $debug = false) + { + $nl = PHP_EOL; + if (Utility::isWindows() && strpos(phpversion(), "5.2") !== false) { + $command = "\"" . $command . "\""; + } + + if ($debug) { + echo '-Running Command: ' . $nl . ' ' . $command . $nl; + } + + $output = []; + $status = 1; + @exec($command, $output, $status); + + if ($debug) { + echo '-Command Output: ' . $nl . ' ' . implode($nl . ' ', $output) . $nl; + } + + return $output; } - $output = []; - $status = 1; - @exec($command, $output, $status); - - if ($debug) { - echo '-Command Output: ' . $nl . ' ' . implode($nl . ' ', $output) . $nl; + /** + * Remove unsafe chars from a filename. + * + * @param string $filename + * + * @return string + */ + public function safeFilename($filename) + { + return trim(preg_replace('/[^\w\s.-]*/i', '', $filename)); } - return $output; -} + public function generateUuid() + { + $key = sprintf + ( + '%04x%04x-%04x-%04x-%04x-%04x%04x%04x', + // 32 bits for "time_low" + mt_rand(0, 0xffff), mt_rand(0, 0xffff), + // 16 bits for "time_mid" + mt_rand(0, 0xffff), + // 16 bits for "time_hi_and_version", + // four most significant bits holds version number 4 + mt_rand(0, 0x0fff) | 0x4000, + // 16 bits, 8 bits for "clk_seq_hi_res", + // 8 bits for "clk_seq_low", + // two most significant bits holds zero and one for variant DCE1.1 + mt_rand(0, 0x3fff) | 0x8000, + // 48 bits for "node" + mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff) + ); -/** - * Remove unsafe chars from a filename. - * - * @param string $filename - * - * @return string - */ -function safeFilename ($filename) -{ - return trim(preg_replace('/[^\w\s.-]*/i', '', $filename)); -} + return $key; + } -function generateUuid() -{ - $key = sprintf - ( - '%04x%04x-%04x-%04x-%04x-%04x%04x%04x', - // 32 bits for "time_low" - mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), - // 16 bits for "time_mid" - mt_rand( 0, 0xffff ), - // 16 bits for "time_hi_and_version", - // four most significant bits holds version number 4 - mt_rand( 0, 0x0fff ) | 0x4000, - // 16 bits, 8 bits for "clk_seq_hi_res", - // 8 bits for "clk_seq_low", - // two most significant bits holds zero and one for variant DCE1.1 - mt_rand( 0, 0x3fff ) | 0x8000, - // 48 bits for "node" - mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ) - ); + public static function startsWith($haystack, $needle) + { + $length = strlen($needle); - return $key; -} + return (substr($haystack, 0, $length) === $needle); + } -function startsWith($haystack, $needle) -{ - $length = strlen($needle); - return (substr($haystack, 0, $length) === $needle); -} + public static function endsWith($haystack, $needle) + { + $length = strlen($needle); + $start = $length * -1; -function endsWith($haystack, $needle) -{ - $length = strlen($needle); - $start = $length * -1; - return (substr($haystack, $start) === $needle); -} + return (substr($haystack, $start) === $needle); + } -function responseXmlToObject($input) -{ - $input = str_replace('<newznab:', '<', $input); - $xml = @simplexml_load_string($input); - return $xml; -} + public function responseXmlToObject($input) + { + $input = str_replace('<newznab:', '<', $input); + $xml = @simplexml_load_string($input); + return $xml; + } + +} \ No newline at end of file diff --git a/lib/copy_this/www/covers/anime/.gitignore b/lib/copy_this/resources/covers/anime/.gitignore similarity index 100% rename from lib/copy_this/www/covers/anime/.gitignore rename to lib/copy_this/resources/covers/anime/.gitignore diff --git a/lib/copy_this/www/covers/audio/.gitignore b/lib/copy_this/resources/covers/audio/.gitignore similarity index 100% rename from lib/copy_this/www/covers/audio/.gitignore rename to lib/copy_this/resources/covers/audio/.gitignore diff --git a/lib/copy_this/www/covers/audiosample/.gitignore b/lib/copy_this/resources/covers/audiosample/.gitignore similarity index 100% rename from lib/copy_this/www/covers/audiosample/.gitignore rename to lib/copy_this/resources/covers/audiosample/.gitignore diff --git a/lib/copy_this/www/covers/book/.gitignore b/lib/copy_this/resources/covers/book/.gitignore similarity index 100% rename from lib/copy_this/www/covers/book/.gitignore rename to lib/copy_this/resources/covers/book/.gitignore diff --git a/lib/copy_this/www/covers/console/.gitignore b/lib/copy_this/resources/covers/console/.gitignore similarity index 100% rename from lib/copy_this/www/covers/console/.gitignore rename to lib/copy_this/resources/covers/console/.gitignore diff --git a/lib/copy_this/www/covers/console/no-cover.jpg b/lib/copy_this/resources/covers/console/no-cover.jpg similarity index 100% rename from lib/copy_this/www/covers/console/no-cover.jpg rename to lib/copy_this/resources/covers/console/no-cover.jpg diff --git a/lib/copy_this/www/covers/games/.gitignore b/lib/copy_this/resources/covers/games/.gitignore similarity index 100% rename from lib/copy_this/www/covers/games/.gitignore rename to lib/copy_this/resources/covers/games/.gitignore diff --git a/lib/copy_this/www/covers/movies/.gitignore b/lib/copy_this/resources/covers/movies/.gitignore similarity index 100% rename from lib/copy_this/www/covers/movies/.gitignore rename to lib/copy_this/resources/covers/movies/.gitignore diff --git a/lib/copy_this/www/covers/music/.gitignore b/lib/copy_this/resources/covers/music/.gitignore similarity index 100% rename from lib/copy_this/www/covers/music/.gitignore rename to lib/copy_this/resources/covers/music/.gitignore diff --git a/lib/copy_this/www/covers/preview/.gitignore b/lib/copy_this/resources/covers/preview/.gitignore similarity index 100% rename from lib/copy_this/www/covers/preview/.gitignore rename to lib/copy_this/resources/covers/preview/.gitignore diff --git a/lib/copy_this/www/covers/sample/.gitignore b/lib/copy_this/resources/covers/sample/.gitignore similarity index 100% rename from lib/copy_this/www/covers/sample/.gitignore rename to lib/copy_this/resources/covers/sample/.gitignore diff --git a/lib/copy_this/www/covers/tvrage/.gitignore b/lib/copy_this/resources/covers/tvrage/.gitignore similarity index 100% rename from lib/copy_this/www/covers/tvrage/.gitignore rename to lib/copy_this/resources/covers/tvrage/.gitignore diff --git a/lib/copy_this/www/covers/video/.gitignore b/lib/copy_this/resources/covers/video/.gitignore similarity index 100% rename from lib/copy_this/www/covers/video/.gitignore rename to lib/copy_this/resources/covers/video/.gitignore diff --git a/lib/copy_this/www/covers/xxx/.gitignore b/lib/copy_this/resources/covers/xxx/.gitignore similarity index 100% rename from lib/copy_this/www/covers/xxx/.gitignore rename to lib/copy_this/resources/covers/xxx/.gitignore diff --git a/lib/copy_this/www/covers/xxx/no-backdrop.jpg b/lib/copy_this/resources/covers/xxx/no-backdrop.jpg similarity index 100% rename from lib/copy_this/www/covers/xxx/no-backdrop.jpg rename to lib/copy_this/resources/covers/xxx/no-backdrop.jpg diff --git a/lib/copy_this/www/covers/xxx/no-cover.jpg b/lib/copy_this/resources/covers/xxx/no-cover.jpg similarity index 100% rename from lib/copy_this/www/covers/xxx/no-cover.jpg rename to lib/copy_this/resources/covers/xxx/no-cover.jpg diff --git a/lib/copy_this/www/resources/logs/.gitignore b/lib/copy_this/resources/logs/.gitignore similarity index 100% rename from lib/copy_this/www/resources/logs/.gitignore rename to lib/copy_this/resources/logs/.gitignore diff --git a/lib/copy_this/www/resources/tmp/.gitignore b/lib/copy_this/resources/tmp/.gitignore similarity index 100% rename from lib/copy_this/www/resources/tmp/.gitignore rename to lib/copy_this/resources/tmp/.gitignore diff --git a/lib/copy_this/www/.htaccess b/lib/copy_this/www/.htaccess new file mode 100644 index 000000000..0068c42ee --- /dev/null +++ b/lib/copy_this/www/.htaccess @@ -0,0 +1,13 @@ +RewriteEngine on +#RewriteBase / + +# Do not process images or CSS files further +RewriteRule \.(css|jpe?g|gif|png|js|ico|mp3|ogg)$ - [L] + +# Leave /admin and /install static +RewriteRule ^(admin|install).*$ - [L] + +# Rewrite web pages to one master page +RewriteRule ^([^/\.]+)/?$ index.php?page=$1 [QSA,L] +RewriteRule ^([^/\.]+)/([^/]+)/?$ index.php?page=$1&id=$2 [QSA,L] +RewriteRule ^([^/\.]+)/([^/]+)/([^/]+)/? index.php?page=$1&id=$2&subpage=$3 [QSA,L] \ No newline at end of file diff --git a/lib/copy_this/www/SPLClassLoader.php b/lib/copy_this/www/SPLClassLoader.php new file mode 100644 index 000000000..f7882cb83 --- /dev/null +++ b/lib/copy_this/www/SPLClassLoader.php @@ -0,0 +1,161 @@ +<?php +/** + * SplClassLoader implementation that implements the technical interoperability + * standards for PHP 5.3 namespaces and class names. + * + * http://groups.google.com/group/php-standards/web/final-proposal + * + * // Example which loads classes for the Doctrine Common package in the + * // Doctrine\Common namespace. + * $classLoader = new SplClassLoader('Doctrine\Common', '/path/to/doctrine'); + * $classLoader->register(); + * + * @author Jonathan H. Wage <jonwage@gmail.com> + * @author Roman S. Borschel <roman@code-factory.org> + * @author Matthew Weier O'Phinney <matthew@zend.com> + * @author Kris Wallsmith <kris.wallsmith@gmail.com> + * @author Fabien Potencier <fabien.potencier@symfony-project.org> + */ +class SplClassLoader +{ + private $_fileExtension = '.php'; + private $_namespace; + private $_includePath; + private $_namespaceSeparator = '\\'; + + /** + * Creates a new <tt>SplClassLoader</tt> that loads classes of the + * specified namespace. + * + * @param string $ns The namespace to use. + */ + public function __construct($ns = null, array $includePath = array()) + { + $this->_namespace = $ns; + foreach ($includePath as &$path) { + if (substr($path, -1) == '/') { + $path = substr($path, 0, -1); + } + } + $this->_includePath = $includePath; + } + + /** + * Sets the namespace separator used by classes in the namespace of this class loader. + * + * @param string $sep The separator to use. + */ + public function setNamespaceSeparator($sep) + { + $this->_namespaceSeparator = $sep; + } + + /** + * Gets the namespace seperator used by classes in the namespace of this class loader. + * + * @return string + */ + public function getNamespaceSeparator() + { + return $this->_namespaceSeparator; + } + + /** + * Sets the base include path for all class files in the namespace of this class loader. + * + * @param string $includePath + */ + public function setIncludePath($includePath) + { + $this->_includePath = $includePath; + } + + /** + * Gets the base include path for all class files in the namespace of this class loader. + * + * @return string $includePath + */ + public function getIncludePath() + { + return $this->_includePath; + } + + /** + * Sets the file extension of class files in the namespace of this class loader. + * + * @param string $fileExtension + */ + public function setFileExtension($fileExtension) + { + $this->_fileExtension = $fileExtension; + } + + /** + * Gets the file extension of class files in the namespace of this class loader. + * + * @return string $fileExtension + */ + public function getFileExtension() + { + return $this->_fileExtension; + } + + /** + * Installs this class loader on the SPL autoload stack. + */ + public function register() + { + spl_autoload_register(array($this, 'loadClass')); + } + + /** + * Uninstalls this class loader from the SPL autoloader stack. + */ + public function unregister() + { + spl_autoload_unregister(array($this, 'loadClass')); + } + + /** + * Loads the given class or interface. + * + * @param string $className The name of the class to load. + * @return void + */ + public function loadClass($className) + { + if (preg_match('#\\\#', $className)) { + // Looks like it's a namespaced class. just clean pathsepearator for now. + $className = str_replace('#\\#', DS, $className); + } + if ($className == 'Smarty') { + require_once SMARTY_DIR . 'Smarty.class.php'; + return; + } + if ($this->_namespace === null || $this->_namespace . $this->_namespaceSeparator === substr($className, 0, strlen($this->_namespace . $this->_namespaceSeparator))) { + $fileName = ''; + $namespace = ''; + if (strtolower(substr($className, 0, 7)) !== 'smarty_') { + if (false !== ($lastNsPos = strripos($className, $this->_namespaceSeparator))) { + $namespace = substr($className, 0, $lastNsPos); + $className = substr($className, $lastNsPos + 1); + $fileName = str_replace($this->_namespaceSeparator, DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR; + } + $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . $this->_fileExtension; + } else { + $fileName = strtolower($className) . '.php'; + } + + if (!empty($this->_includePath)) { + foreach ($this->_includePath as $path) { + $spec = $path . DIRECTORY_SEPARATOR . $fileName; + if (file_exists($spec)) { + require_once $spec; + return; + } + } + } + require_once $fileName; + } + } +} diff --git a/lib/copy_this/www/admin/ajax.php b/lib/copy_this/www/admin/ajax.php index b7ba576f7..a2c24457a 100644 --- a/lib/copy_this/www/admin/ajax.php +++ b/lib/copy_this/www/admin/ajax.php @@ -5,13 +5,7 @@ if (!isset($_GET['action'])) { exit(); } - -require_once("config.php"); -require_once(WWW_DIR."/lib/adminpage.php"); -require_once(WWW_DIR."/lib/binaries.php"); -require_once(WWW_DIR."/lib/Regexes.php"); -require_once(WWW_DIR."/lib/groups.php"); -require_once(WWW_DIR."/lib/releasecomments.php"); +require_once './config.php'; // Make sure the user is an admin and logged in. $admin = new AdminPage; diff --git a/lib/copy_this/www/admin/ajax_binaryblacklist-list.php b/lib/copy_this/www/admin/ajax_binaryblacklist-list.php new file mode 100644 index 000000000..8b89162f2 --- /dev/null +++ b/lib/copy_this/www/admin/ajax_binaryblacklist-list.php @@ -0,0 +1,13 @@ +<?php +require_once './config.php'; + +// login check +$admin = new AdminPage; +$bin = new Binaries(); + +if (isset($_GET['action']) && $_GET['action'] == "2") +{ + $id = (int)$_GET['bin_id']; + $bin->deleteBlacklist($id); + print "Blacklist $id deleted."; +} diff --git a/lib/copy_this/www/admin/ajax_group-edit.php b/lib/copy_this/www/admin/ajax_group-edit.php index 705e4812a..d5e03ba77 100644 --- a/lib/copy_this/www/admin/ajax_group-edit.php +++ b/lib/copy_this/www/admin/ajax_group-edit.php @@ -1,7 +1,5 @@ <?php -require_once("config.php"); -require_once(WWW_DIR."/lib/adminpage.php"); -require_once(WWW_DIR."/lib/groups.php"); +require_once './config.php'; $admin = new AdminPage; $group = new Groups(['Settings' => $admin->settings]); diff --git a/lib/copy_this/www/admin/ajax_regex-list.php b/lib/copy_this/www/admin/ajax_regex-list.php new file mode 100644 index 000000000..57f208c3f --- /dev/null +++ b/lib/copy_this/www/admin/ajax_regex-list.php @@ -0,0 +1,13 @@ +<?php +require_once './config.php'; + +// login check +$admin = new AdminPage; +$regex = new ReleaseRegex(); + +if (isset($_GET['action']) && $_GET['action'] == "2") +{ + $id = (int)$_GET['regex_id']; + $regex->delete($id); + print "Regex $id deleted."; +} diff --git a/lib/copy_this/www/admin/ajax_regex.php b/lib/copy_this/www/admin/ajax_regex.php index dcae8a6e6..c4a0bc5ad 100644 --- a/lib/copy_this/www/admin/ajax_regex.php +++ b/lib/copy_this/www/admin/ajax_regex.php @@ -1,11 +1,8 @@ <?php -require_once("config.php"); -require_once(WWW_DIR."/lib/adminpage.php"); -require_once(WWW_DIR."/lib/CollectionsCleaning.php"); -require_once(WWW_DIR."/lib/binaries.php"); +require_once './config.php'; // Login Check -$admin = new AdminPage; +$admin = new \AdminPage; if (!isset($_GET['action'])) { exit(); @@ -14,13 +11,13 @@ if (!isset($_GET['action'])) { switch($_GET['action']) { case 1: $id = (int) $_GET['col_id']; - (new CollectionsCleaning(['Settings' => $admin->settings]))->deleteRegex($id); + (new \Regexes(['Settings' => $admin->settings]))->deleteRegex($id); print "Regex $id deleted."; break; case 2: $id = (int) $_GET['bin_id']; - (new Binaries(['Settings' => $admin->settings]))->deleteBlacklist($id); + (new \Binaries(['Settings' => $admin->settings]))->deleteBlacklist($id); print "Blacklist $id deleted."; break; } \ No newline at end of file diff --git a/lib/copy_this/www/admin/ajax_sharing_settings.php b/lib/copy_this/www/admin/ajax_sharing_settings.php index d6dc3a7d3..d57e713a7 100644 --- a/lib/copy_this/www/admin/ajax_sharing_settings.php +++ b/lib/copy_this/www/admin/ajax_sharing_settings.php @@ -1,12 +1,10 @@ <?php -require_once("config.php"); -require_once(WWW_DIR."/lib/framework/db.php"); -require_once(WWW_DIR."/lib/adminpage.php"); +require_once './config.php'; // Login check. $admin = new AdminPage; -$db = new DB(); +$db = new newznab\db\DB(); if (isset($_GET['site_ID']) && isset($_GET['site_status'])) { $db->queryExec(sprintf('UPDATE sharing_sites SET enabled = %d WHERE id = %d', $_GET['site_status'], $_GET['site_ID'])); diff --git a/lib/copy_this/www/admin/ajax_welcome_msg.php b/lib/copy_this/www/admin/ajax_welcome_msg.php new file mode 100644 index 000000000..3d743a66a --- /dev/null +++ b/lib/copy_this/www/admin/ajax_welcome_msg.php @@ -0,0 +1,15 @@ +<?php +require_once './config.php'; + +// login check +$admin = new AdminPage; +$s = new Sites(); + +if (isset($_GET['action'])) +{ + if ($_GET['action'] == "1") + $s->updateItem("showadminwelcome", 1); + else + $s->updateItem("showadminwelcome", 0); +} + diff --git a/lib/copy_this/www/admin/anidb-delete.php b/lib/copy_this/www/admin/anidb-delete.php new file mode 100644 index 000000000..681118728 --- /dev/null +++ b/lib/copy_this/www/admin/anidb-delete.php @@ -0,0 +1,13 @@ +<?php +require_once './config.php'; + +$page = new AdminPage(); + +if (isset($_GET['id'])) +{ + $AniDB = new AniDB(); + $AniDB->deleteTitle($_GET['id']); +} + +$referrer = $_SERVER['HTTP_REFERER']; +header("Location: " . $referrer); diff --git a/lib/copy_this/www/admin/anidb-edit.php b/lib/copy_this/www/admin/anidb-edit.php new file mode 100644 index 000000000..a1c05eaa8 --- /dev/null +++ b/lib/copy_this/www/admin/anidb-edit.php @@ -0,0 +1,42 @@ +<?php + +require_once './config.php'; + +$page = new AdminPage(); +$AniDB = new AniDB(); +$id = 0; + +// set the current action +$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 'view'; + +switch($action) +{ + case 'submit': + + $AniDB->updateTitle($_POST["anidbID"], $_POST["title"], $_POST["type"], $_POST["startdate"], $_POST["enddate"], $_POST["related"], $_POST["creators"], $_POST["description"], $_POST["rating"], $_POST["categories"], $_POST["characters"], $_POST["epnos"], $_POST["airdates"], $_POST["episodetitles"]); + + if(isset($_POST['from']) && !empty($_POST['from'])) + { + header("Location:".$_POST['from']); + exit; + } + + header("Location:".WWW_TOP."/anidb-list.php"); + break; + + case 'view': + default: + + if (isset($_GET["id"])) + { + $page->title = "AniDB Edit"; + $AniDBAPIArray = $AniDB->getAnimeInfo($_GET["id"]); + $page->smarty->assign('anime', $AniDBAPIArray); + } + + break; +} + +$page->title="Edit AniDB Data"; +$page->content = $page->smarty->fetch('anidb-edit.tpl'); +$page->render(); diff --git a/lib/copy_this/www/admin/anidb-list.php b/lib/copy_this/www/admin/anidb-list.php new file mode 100644 index 000000000..8a68915c0 --- /dev/null +++ b/lib/copy_this/www/admin/anidb-list.php @@ -0,0 +1,33 @@ +<?php + +require_once './config.php'; + +$page = new AdminPage(); + +$AniDB = new AniDB(); + +$page->title = "AniDB List"; + +$aname = ""; +if (isset($_REQUEST['animetitle']) && !empty($_REQUEST['animetitle'])) + $aname = $_REQUEST['animetitle']; + +$animecount = $AniDB->getAnimeCount($aname); + +$offset = isset($_REQUEST["offset"]) ? $_REQUEST["offset"] : 0; +$asearch = ($aname != "") ? 'animetitle='.$aname.'&' : ''; + +$page->smarty->assign('pagertotalitems',$animecount); +$page->smarty->assign('pageroffset',$offset); +$page->smarty->assign('pageritemsperpage',ITEMS_PER_PAGE); +$page->smarty->assign('pagerquerybase', WWW_TOP."/anidb-list.php?".$asearch."&offset="); +$pager = $page->smarty->fetch("pager.tpl"); +$page->smarty->assign('pager', $pager); + +$page->smarty->assign('animetitle',$aname); + +$anidblist = $AniDB->getAnimeRange($offset, ITEMS_PER_PAGE, $aname); +$page->smarty->assign('anidblist',$anidblist); + +$page->content = $page->smarty->fetch('anidb-list.tpl'); +$page->render(); diff --git a/lib/copy_this/www/admin/anidb-remove.php b/lib/copy_this/www/admin/anidb-remove.php new file mode 100644 index 000000000..017bf45ff --- /dev/null +++ b/lib/copy_this/www/admin/anidb-remove.php @@ -0,0 +1,14 @@ +<?php + +require_once './config.php'; + +$page = new AdminPage(); + +$releases = new Releases(); +$num = (isset($_GET["id"])) ? $releases->removeAnidbIdFromReleases($_GET["id"]) : 0; + +$page->smarty->assign('numtv',$num); + +$page->title = "Remove anidbID from Releases"; +$page->content = $page->smarty->fetch('anidb-remove.tpl'); +$page->render(); diff --git a/lib/copy_this/www/admin/binaryblacklist-edit.php b/lib/copy_this/www/admin/binaryblacklist-edit.php new file mode 100644 index 000000000..2edf52103 --- /dev/null +++ b/lib/copy_this/www/admin/binaryblacklist-edit.php @@ -0,0 +1,78 @@ +<?php + +require_once './config.php'; + +$page = new AdminPage(); +$bin = new Binaries(); +$id = 0; + +// set the current action +$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 'view'; + +switch($action) +{ + case 'submit': + + if ($_POST["groupname"] == "") + { + $page->smarty->assign('error', "Group must be a valid usenet group"); + break; + } + + if ($_POST["regex"] == "") + { + $page->smarty->assign('error', "Regex cannot be empty"); + break; + } + + if ($_POST["id"] == "") + { + $bin->addBlacklist($_POST); + } + else + { + $ret = $bin->updateBlacklist($_POST); + } + header("Location:".WWW_TOP."/binaryblacklist-list.php"); + break; + case 'addtest': + if (isset($_GET['regex']) && isset($_GET['groupname'])) { + $r = array('groupname'=>$_GET['groupname'], 'regex'=>$_GET['regex'], 'ordinal'=>'1', 'status'=>'1'); + $page->smarty->assign('regex', $r); + } + break; + case 'view': + default: + + if (isset($_GET["id"])) + { + $page->title = "Binary Black/Whitelist Edit"; + $id = $_GET["id"]; + + $r = $bin->getBlacklistByID($id); + + } + else + { + $page->title = "Binary Black/Whitelist Add"; + $r = array(); + $r["status"] = 1; + $r["optype"] = 1; + $r["msgcol"] = 1; + } + $page->smarty->assign('regex', $r); + + break; +} + +$page->smarty->assign('status_ids', array(Category::STATUS_ACTIVE,Category::STATUS_INACTIVE)); +$page->smarty->assign('status_names', array( 'Yes', 'No')); + +$page->smarty->assign('optype_ids', array(1,2)); +$page->smarty->assign('optype_names', array( 'Black', 'White')); + +$page->smarty->assign('msgcol_ids', array(Binaries::BLACKLIST_FIELD_SUBJECT, Binaries::BLACKLIST_FIELD_FROM, Binaries::BLACKLIST_FIELD_MESSAGEID)); +$page->smarty->assign('msgcol_names', array( 'Subject', 'Poster', 'MessageId')); + +$page->content = $page->smarty->fetch('binaryblacklist-edit.tpl'); +$page->render(); diff --git a/lib/copy_this/www/admin/binaryblacklist-list.php b/lib/copy_this/www/admin/binaryblacklist-list.php new file mode 100644 index 000000000..4e93b794f --- /dev/null +++ b/lib/copy_this/www/admin/binaryblacklist-list.php @@ -0,0 +1,15 @@ +<?php + +require_once './config.php'; + +$page = new AdminPage(); + +$bin = new Binaries(); + +$page->title = "Binary Black/Whitelist List"; + +$binlist = $bin->getBlacklist(false); +$page->smarty->assign('binlist', $binlist); + +$page->content = $page->smarty->fetch('binaryblacklist-list.tpl'); +$page->render(); diff --git a/lib/copy_this/www/admin/book-edit.php b/lib/copy_this/www/admin/book-edit.php new file mode 100644 index 000000000..1d2cc720c --- /dev/null +++ b/lib/copy_this/www/admin/book-edit.php @@ -0,0 +1,53 @@ +<?php + +require_once './config.php'; + +$page = new AdminPage(); +$book = new Book(); +$gen = new Genres(); +$id = 0; + +// set the current action +$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 'view'; + +if (isset($_REQUEST["id"])) +{ + $id = $_REQUEST["id"]; + $b = $book->getBookInfo($id); + + if (!$b) { + $page->show404(); + } + + switch($action) + { + case 'submit': + $coverLoc = WWW_DIR."covers/book/".$id.'.jpg'; + + if($_FILES['cover']['size'] > 0) + { + $tmpName = $_FILES['cover']['tmp_name']; + $file_info = getimagesize($tmpName); + if(!empty($file_info)) + { + move_uploaded_file($_FILES['cover']['tmp_name'], $coverLoc); + } + } + + $_POST['cover'] = (file_exists($coverLoc)) ? 1 : 0; + $_POST['publishdate'] = (empty($_POST['publishdate']) || !strtotime($_POST['publishdate'])) ? $con['publishdate'] : date("Y-m-d H:i:s", strtotime($_POST['publishdate'])); + $book->update($id, $_POST["title"], $_POST['asin'], $_POST['url'], $_POST["author"], $_POST["publisher"], $_POST["publishdate"], $_POST["cover"]); + + header("Location:".WWW_TOP."/book-list.php"); + die(); + break; + case 'view': + default: + $page->title = "Book Edit"; + $page->smarty->assign('book', $b); + break; + } +} + +$page->content = $page->smarty->fetch('book-edit.tpl'); +$page->render(); diff --git a/lib/copy_this/www/admin/book-list.php b/lib/copy_this/www/admin/book-list.php new file mode 100644 index 000000000..1b9c4d83d --- /dev/null +++ b/lib/copy_this/www/admin/book-list.php @@ -0,0 +1,26 @@ +<?php + +require_once './config.php'; + +$page = new AdminPage(); + +$book = new Book(); + +$page->title = "Book List"; + +$concount = $book->getCount(); + +$offset = isset($_REQUEST["offset"]) ? $_REQUEST["offset"] : 0; +$page->smarty->assign('pagertotalitems',$concount); +$page->smarty->assign('pageroffset',$offset); +$page->smarty->assign('pageritemsperpage',ITEMS_PER_PAGE); +$page->smarty->assign('pagerquerybase', WWW_TOP."/book-list.php?offset="); +$pager = $page->smarty->fetch("pager.tpl"); +$page->smarty->assign('pager', $pager); + +$booklist = $book->getRange($offset, ITEMS_PER_PAGE); + +$page->smarty->assign('booklist',$booklist); + +$page->content = $page->smarty->fetch('book-list.tpl'); +$page->render(); diff --git a/lib/copy_this/www/admin/category-edit.php b/lib/copy_this/www/admin/category-edit.php new file mode 100644 index 000000000..69413e5ee --- /dev/null +++ b/lib/copy_this/www/admin/category-edit.php @@ -0,0 +1,39 @@ +<?php + +require_once './config.php'; + +$page = new AdminPage(); +$category = new Category(); +$id = 0; + +// set the current action +$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 'view'; + +switch($action) +{ + case 'submit': + $ret = $category->update($_POST["id"], $_POST["status"], $_POST["description"], + $_POST["disablepreview"], $_POST["minsizetoformrelease"], $_POST["maxsizetoformrelease"]); + header("Location:".WWW_TOP."/category-list.php"); + break; + case 'view': + default: + + if (isset($_GET["id"])) + { + $page->title = "Category Edit"; + $id = $_GET["id"]; + + $cat = $category->getByID($id); + + $page->smarty->assign('category', $cat); + } + + break; +} + +$page->smarty->assign('status_ids', array(Category::STATUS_ACTIVE,Category::STATUS_INACTIVE)); +$page->smarty->assign('status_names', array( 'Yes', 'No')); + +$page->content = $page->smarty->fetch('category-edit.tpl'); +$page->render(); diff --git a/lib/copy_this/www/admin/category-list.php b/lib/copy_this/www/admin/category-list.php new file mode 100644 index 000000000..c140b236d --- /dev/null +++ b/lib/copy_this/www/admin/category-list.php @@ -0,0 +1,16 @@ +<?php + +require_once './config.php'; + +$page = new AdminPage(); + +$category = new Category(); + +$page->title = "Category List"; + +$categorylist = $category->getFlat(); +$page->smarty->assign('categorylist',$categorylist); + +$page->content = $page->smarty->fetch('category-list.tpl'); +$page->render(); + diff --git a/lib/copy_this/www/admin/category_regexes-edit.php b/lib/copy_this/www/admin/category_regexes-edit.php index 40d080058..7fcd22019 100644 --- a/lib/copy_this/www/admin/category_regexes-edit.php +++ b/lib/copy_this/www/admin/category_regexes-edit.php @@ -1,7 +1,6 @@ <?php -require_once 'config.php'; -require_once(WWW_DIR."/lib/adminpage.php"); -require_once(WWW_DIR."/lib/Regexes.php"); +require_once './config.php'; + $page = new AdminPage(); $regexes = new Regexes(['Settings' => $page->settings, 'Table_Name' => 'category_regexes']); diff --git a/lib/copy_this/www/admin/category_regexes-list.php b/lib/copy_this/www/admin/category_regexes-list.php index 0d1e3fece..10296d0ff 100644 --- a/lib/copy_this/www/admin/category_regexes-list.php +++ b/lib/copy_this/www/admin/category_regexes-list.php @@ -1,7 +1,5 @@ <?php -require_once 'config.php'; -require_once(WWW_DIR."/lib/adminpage.php"); -require_once(WWW_DIR."/lib/Regexes.php"); +require_once './config.php'; $page = new AdminPage(); $regexes = new Regexes(['Settings' => $page->settings, 'Table_Name' => 'category_regexes']); diff --git a/lib/copy_this/www/admin/collection_regexes-edit.php b/lib/copy_this/www/admin/collection_regexes-edit.php index c3ee452f5..57792b7a5 100644 --- a/lib/copy_this/www/admin/collection_regexes-edit.php +++ b/lib/copy_this/www/admin/collection_regexes-edit.php @@ -1,7 +1,5 @@ <?php -require_once 'config.php'; -require_once(WWW_DIR."/lib/adminpage.php"); -require_once(WWW_DIR."/lib/Regexes.php"); +require_once './config.php'; $page = new AdminPage(); $regexes = new Regexes(['Settings' => $page->settings, 'Table_Name' => 'collection_regexes']); diff --git a/lib/copy_this/www/admin/collection_regexes-list.php b/lib/copy_this/www/admin/collection_regexes-list.php index f28b2639e..992c315bd 100644 --- a/lib/copy_this/www/admin/collection_regexes-list.php +++ b/lib/copy_this/www/admin/collection_regexes-list.php @@ -1,7 +1,5 @@ <?php require_once './config.php'; -require_once(WWW_DIR."/lib/adminpage.php"); -require_once(WWW_DIR."/lib/Regexes.php"); $page = new AdminPage(); $regexes = new Regexes(['Settings' => $page->settings, 'Table_Name' => 'collection_regexes']); diff --git a/lib/copy_this/www/admin/collection_regexes-test.php b/lib/copy_this/www/admin/collection_regexes-test.php index fa5b3b0cb..f81f3c5e8 100644 --- a/lib/copy_this/www/admin/collection_regexes-test.php +++ b/lib/copy_this/www/admin/collection_regexes-test.php @@ -1,7 +1,5 @@ <?php require_once './config.php'; -require_once(WWW_DIR."/lib/adminpage.php"); -require_once(WWW_DIR."/lib/Regexes.php"); $page = new AdminPage(); diff --git a/lib/copy_this/www/admin/comments-delete.php b/lib/copy_this/www/admin/comments-delete.php new file mode 100644 index 000000000..56868fc04 --- /dev/null +++ b/lib/copy_this/www/admin/comments-delete.php @@ -0,0 +1,14 @@ +<?php +require_once './config.php'; + +$page = new AdminPage(); + +if (isset($_GET['id'])) +{ + $rc = new ReleaseComments(); + $rc->deleteComment($_GET['id']); +} + +$referrer = $_SERVER['HTTP_REFERER']; +header("Location: " . $referrer); + diff --git a/lib/copy_this/www/admin/comments-list.php b/lib/copy_this/www/admin/comments-list.php new file mode 100644 index 000000000..714200c83 --- /dev/null +++ b/lib/copy_this/www/admin/comments-list.php @@ -0,0 +1,24 @@ +<?php + +require_once './config.php'; + +$page = new AdminPage(); + +$releases = new ReleaseComments(); + +$page->title = "Comments List"; + +$commentcount = $releases->getCommentCount(); +$offset = isset($_REQUEST["offset"]) ? $_REQUEST["offset"] : 0; +$page->smarty->assign('pagertotalitems',$commentcount); +$page->smarty->assign('pageroffset',$offset); +$page->smarty->assign('pageritemsperpage',ITEMS_PER_PAGE); +$page->smarty->assign('pagerquerybase', WWW_TOP."/comments-list.php?offset="); +$pager = $page->smarty->fetch("pager.tpl"); +$page->smarty->assign('pager', $pager); + +$commentslist = $releases->getCommentsRange($offset, ITEMS_PER_PAGE); +$page->smarty->assign('commentslist',$commentslist); + +$page->content = $page->smarty->fetch('comments-list.tpl'); +$page->render(); diff --git a/lib/copy_this/www/admin/config.php b/lib/copy_this/www/admin/config.php new file mode 100644 index 000000000..efe6b3aba --- /dev/null +++ b/lib/copy_this/www/admin/config.php @@ -0,0 +1,2 @@ +<?php +require_once("../config.php"); diff --git a/lib/copy_this/www/admin/console-edit.php b/lib/copy_this/www/admin/console-edit.php new file mode 100644 index 000000000..6cd4d68bb --- /dev/null +++ b/lib/copy_this/www/admin/console-edit.php @@ -0,0 +1,56 @@ +<?php + +require_once './config.php'; + +$page = new AdminPage(); +$console = new Console(); +$gen = new Genres(); +$id = 0; + +// set the current action +$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 'view'; + +if (isset($_REQUEST["id"])) +{ + $id = $_REQUEST["id"]; + $con = $console->getConsoleInfo($id); + + if (!$con) { + $page->show404(); + } + + switch($action) + { + case 'submit': + $coverLoc = WWW_DIR."covers/console/".$id.'.jpg'; + + if($_FILES['cover']['size'] > 0) + { + $tmpName = $_FILES['cover']['tmp_name']; + $file_info = getimagesize($tmpName); + if(!empty($file_info)) + { + move_uploaded_file($_FILES['cover']['tmp_name'], $coverLoc); + } + } + + $_POST['cover'] = (file_exists($coverLoc)) ? 1 : 0; + $_POST['salesrank'] = (empty($_POST['salesrank']) || !ctype_digit($_POST['salesrank'])) ? "null" : $_POST['salesrank']; + $_POST['releasedate'] = (empty($_POST['releasedate']) || !strtotime($_POST['releasedate'])) ? $con['releasedate'] : date("Y-m-d H:i:s", strtotime($_POST['releasedate'])); + + $console->update($id, $_POST["title"], $_POST['asin'], $_POST['url'], $_POST["salesrank"], $_POST["platform"], $_POST["publisher"], $_POST["releasedate"], $_POST["esrb"], $_POST["cover"], $_POST["genre"]); + + header("Location:".WWW_TOP."/console-list.php"); + die(); + break; + case 'view': + default: + $page->title = "Console Edit"; + $page->smarty->assign('console', $con); + $page->smarty->assign('genres', $gen->getGenres(Genres::CONSOLE_TYPE)); + break; + } +} + +$page->content = $page->smarty->fetch('console-edit.tpl'); +$page->render(); diff --git a/lib/copy_this/www/admin/console-list.php b/lib/copy_this/www/admin/console-list.php new file mode 100644 index 000000000..63a570090 --- /dev/null +++ b/lib/copy_this/www/admin/console-list.php @@ -0,0 +1,26 @@ +<?php + +require_once './config.php'; + +$page = new AdminPage(); + +$con = new Console(); + +$page->title = "Console List"; + +$concount = $con->getCount(); + +$offset = isset($_REQUEST["offset"]) ? $_REQUEST["offset"] : 0; +$page->smarty->assign('pagertotalitems',$concount); +$page->smarty->assign('pageroffset',$offset); +$page->smarty->assign('pageritemsperpage',ITEMS_PER_PAGE); +$page->smarty->assign('pagerquerybase', WWW_TOP."/console-list.php?offset="); +$pager = $page->smarty->fetch("pager.tpl"); +$page->smarty->assign('pager', $pager); + +$consolelist = $con->getRange($offset, ITEMS_PER_PAGE); + +$page->smarty->assign('consolelist',$consolelist); + +$page->content = $page->smarty->fetch('console-list.tpl'); +$page->render(); diff --git a/lib/copy_this/www/admin/content-add.php b/lib/copy_this/www/admin/content-add.php new file mode 100644 index 000000000..6ed423d96 --- /dev/null +++ b/lib/copy_this/www/admin/content-add.php @@ -0,0 +1,68 @@ +<?php + +require_once './config.php'; + +$page = new AdminPage(); +$contents = new Contents(); +$id = 0; + +// set the current action +$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 'view'; + +switch($action) +{ + case 'add': + $page->title = "Content Add"; + $content = array(); + $content["showinmenu"] = "1"; + $content["status"] = "1"; + $content["contenttype"] = "2"; + $page->smarty->assign('content',$content); + break; + + case 'submit': + // + // validate and add or update + // + $returnid = 0; + if (!isset($_POST["id"]) || $_POST["id"]=="") + { + $returnid = $contents->add($_POST); + } + else + { + $content = $contents->update($_POST); + $returnid = $_POST["id"]; + } + header("Location:content-add.php?id=".$returnid); + + break; + case 'view': + default: + + if (isset($_GET["id"])) + { + $page->title = "Content Edit"; + $id = $_GET["id"]; + + $content = $contents->getByID($id, Users::ROLE_ADMIN); + $page->smarty->assign('content', $content); + } + + break; +} + +$page->smarty->assign('status_ids', array(1,0)); +$page->smarty->assign('status_names', array( 'Enabled', 'Disabled')); + +$page->smarty->assign('yesno_ids', array(1,0)); +$page->smarty->assign('yesno_names', array( 'Yes', 'No')); + +$contenttypelist = array("1" => "Useful Link", "2" => "Article", "3" => "Homepage"); +$page->smarty->assign('contenttypelist', $contenttypelist); + +$rolelist = array("0" => "Everyone", "1" => "Logged in Users", "2" => "Admins"); +$page->smarty->assign('rolelist', $rolelist); + +$page->content = $page->smarty->fetch('content-add.tpl'); +$page->render(); diff --git a/lib/copy_this/www/admin/content-delete.php b/lib/copy_this/www/admin/content-delete.php new file mode 100644 index 000000000..aff67f04c --- /dev/null +++ b/lib/copy_this/www/admin/content-delete.php @@ -0,0 +1,15 @@ +<?php + +require_once './config.php'; + +$page = new AdminPage(); + +if (isset($_GET['id'])) +{ + $contents = new Contents(); + $contents->delete($_GET['id']); +} + +$referrer = $_SERVER['HTTP_REFERER']; +header("Location: " . $referrer); + diff --git a/lib/copy_this/www/admin/content-list.php b/lib/copy_this/www/admin/content-list.php new file mode 100644 index 000000000..0432fa6e8 --- /dev/null +++ b/lib/copy_this/www/admin/content-list.php @@ -0,0 +1,15 @@ +<?php + +require_once './config.php'; + +$page = new AdminPage(); + +$contents = new Contents(); +$contentlist = $contents->getAll(); +$page->smarty->assign('contentlist',$contentlist); + +$page->title = "Content List"; + +$page->content = $page->smarty->fetch('content-list.tpl'); +$page->render(); + diff --git a/lib/copy_this/www/admin/db-optimise.php b/lib/copy_this/www/admin/db-optimise.php new file mode 100644 index 000000000..978d04a28 --- /dev/null +++ b/lib/copy_this/www/admin/db-optimise.php @@ -0,0 +1,14 @@ +<?php + +require_once './config.php'; + +use newznab\db\DB; +$page = new AdminPage(); + +$db = new DB; +$tablelist = $db->optimise(); + +$page->title = "DB Table Optimise"; +$page->smarty->assign('tablelist',$tablelist); +$page->content = $page->smarty->fetch('db-optimise.tpl'); +$page->render(); diff --git a/lib/copy_this/www/admin/forum-delete.php b/lib/copy_this/www/admin/forum-delete.php new file mode 100644 index 000000000..e672021db --- /dev/null +++ b/lib/copy_this/www/admin/forum-delete.php @@ -0,0 +1,16 @@ +<?php +require_once './config.php'; + +$page = new AdminPage(); + +if (isset($_GET['id'])) +{ + $forum = new Forum(); + $forum->deletePost($_GET['id']); +} + +if (isset($_GET['from'])) + $referrer = $_GET['from']; +else + $referrer = $_SERVER['HTTP_REFERER']; +header("Location: " . $referrer); diff --git a/lib/copy_this/www/admin/game-edit.php b/lib/copy_this/www/admin/game-edit.php index 5a07bdab5..ee508cb18 100644 --- a/lib/copy_this/www/admin/game-edit.php +++ b/lib/copy_this/www/admin/game-edit.php @@ -1,8 +1,5 @@ <?php -require_once("config.php"); -require_once(WWW_DIR."/lib/adminpage.php"); -require_once(WWW_DIR."/lib/Games.php"); -require_once(WWW_DIR."/lib/genres.php"); +require_once './config.php'; $page = new AdminPage(); $games = new Games(['Settings' => $page->settings]); diff --git a/lib/copy_this/www/admin/game-list.php b/lib/copy_this/www/admin/game-list.php index 02b5c050e..e6c94d193 100644 --- a/lib/copy_this/www/admin/game-list.php +++ b/lib/copy_this/www/admin/game-list.php @@ -1,7 +1,5 @@ <?php -require_once("config.php"); -require_once(WWW_DIR."/lib/adminpage.php"); -require_once(WWW_DIR."/lib/Games.php"); +require_once './config.php'; $page = new AdminPage(); $game = new Games(['Settings' => $page->settings]); diff --git a/lib/copy_this/www/admin/group-bulk.php b/lib/copy_this/www/admin/group-bulk.php index 4ba66e2ff..1a0a67472 100644 --- a/lib/copy_this/www/admin/group-bulk.php +++ b/lib/copy_this/www/admin/group-bulk.php @@ -1,8 +1,6 @@ <?php -require_once("config.php"); -require_once(WWW_DIR."/lib/adminpage.php"); -require_once(WWW_DIR."/lib/groups.php"); +require_once './config.php'; $page = new AdminPage(); diff --git a/lib/copy_this/www/admin/group-edit.php b/lib/copy_this/www/admin/group-edit.php index 15b00a7c3..1dc66d7b6 100644 --- a/lib/copy_this/www/admin/group-edit.php +++ b/lib/copy_this/www/admin/group-edit.php @@ -1,9 +1,6 @@ <?php -require_once("config.php"); -require_once(WWW_DIR."/lib/adminpage.php"); -require_once(WWW_DIR."/lib/groups.php"); -require_once(WWW_DIR."/lib/category.php"); +require_once './config.php'; $page = new AdminPage(); $groups = new Groups(['Settings' => $page->settings]); diff --git a/lib/copy_this/www/admin/group-list-active.php b/lib/copy_this/www/admin/group-list-active.php index 244f866f1..9e61326cc 100644 --- a/lib/copy_this/www/admin/group-list-active.php +++ b/lib/copy_this/www/admin/group-list-active.php @@ -1,7 +1,5 @@ <?php -require_once("config.php"); -require_once(WWW_DIR."/lib/adminpage.php"); -require_once(WWW_DIR."/lib/groups.php"); +require_once './config.php'; $page = new AdminPage(); $groups = new Groups(['Settings' => $page->settings]); diff --git a/lib/copy_this/www/admin/group-list-inactive.php b/lib/copy_this/www/admin/group-list-inactive.php index 939cf6598..3b49e88af 100644 --- a/lib/copy_this/www/admin/group-list-inactive.php +++ b/lib/copy_this/www/admin/group-list-inactive.php @@ -1,7 +1,5 @@ <?php -require_once("config.php"); -require_once(WWW_DIR."/lib/adminpage.php"); -require_once(WWW_DIR."/lib/groups.php"); +require_once './config.php'; $page = new AdminPage(); $groups = new Groups(['Settings' => $page->settings]); diff --git a/lib/copy_this/www/admin/group-list.php b/lib/copy_this/www/admin/group-list.php index 894a321e9..c0a27c431 100644 --- a/lib/copy_this/www/admin/group-list.php +++ b/lib/copy_this/www/admin/group-list.php @@ -1,8 +1,6 @@ <?php -require_once("config.php"); -require_once(WWW_DIR."/lib/adminpage.php"); -require_once(WWW_DIR."/lib/groups.php"); +require_once './config.php'; $page = new AdminPage(); $groups = new Groups(['Settings' => $page->settings]); diff --git a/lib/copy_this/www/admin/index.php b/lib/copy_this/www/admin/index.php index 34fa4dc51..d65829ff8 100644 --- a/lib/copy_this/www/admin/index.php +++ b/lib/copy_this/www/admin/index.php @@ -1,9 +1,8 @@ <?php -require_once("config.php"); -require_once(WWW_DIR."/lib/adminpage.php"); -require_once(WWW_DIR."/lib/site.php"); -require_once(WWW_DIR."/lib/framework/db.php"); +require_once './config.php'; + +use newznab\db\DB; $page = new AdminPage(); diff --git a/lib/copy_this/www/admin/menu-delete.php b/lib/copy_this/www/admin/menu-delete.php new file mode 100644 index 000000000..f5a8211f6 --- /dev/null +++ b/lib/copy_this/www/admin/menu-delete.php @@ -0,0 +1,14 @@ +<?php +require_once './config.php'; + +$page = new AdminPage(); + +if (isset($_GET['id'])) +{ + $menu = new Menu(); + $menu->delete($_GET['id']); +} + +$referrer = $_SERVER['HTTP_REFERER']; +header("Location: " . $referrer); + diff --git a/lib/copy_this/www/admin/menu-edit.php b/lib/copy_this/www/admin/menu-edit.php new file mode 100644 index 000000000..216e54e33 --- /dev/null +++ b/lib/copy_this/www/admin/menu-edit.php @@ -0,0 +1,60 @@ +<?php + +require_once './config.php'; + +$page = new AdminPage(); +$page->title = "Menu Add"; +$menu = new Menu(); +$users = new Users(); +$id = 0; + +//get the user roles +$userroles = $users->getRoles(); +$roles = array(); +foreach ($userroles as $r) { + $roles[$r['ID']] = $r['name']; +} + +// set the current action +$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 'view'; + +switch($action) +{ + case 'submit': + + if ($_POST["id"] == "") + { + $menu->add($_POST); + } + else + { + $ret = $menu->update($_POST); + } + + header("Location:".WWW_TOP."/menu-list.php"); + break; + case 'view': + default: + + if (isset($_GET["id"])) + { + $page->title = "Menu Edit"; + $id = $_GET["id"]; + + $menurow = $menu->getByID($id); + + $page->smarty->assign('menu', $menurow); + } + + break; +} + +$page->smarty->assign('yesno_ids', array(1,0)); +$page->smarty->assign('yesno_names', array( 'Yes', 'No')); + +$page->smarty->assign('role_ids', array_keys($roles)); +$page->smarty->assign('role_names', $roles); + +$page->content = $page->smarty->fetch('menu-edit.tpl'); +$page->render(); + diff --git a/lib/copy_this/www/admin/menu-list.php b/lib/copy_this/www/admin/menu-list.php new file mode 100644 index 000000000..ac0007d54 --- /dev/null +++ b/lib/copy_this/www/admin/menu-list.php @@ -0,0 +1,16 @@ +<?php + +require_once './config.php'; + +$page = new AdminPage(); + +$menu = new Menu(); + +$page->title = "Menu List"; + +$menulist = $menu->getAll(); +$page->smarty->assign('menulist',$menulist); + +$page->content = $page->smarty->fetch('menu-list.tpl'); +$page->render(); + diff --git a/lib/copy_this/www/admin/movie-add.php b/lib/copy_this/www/admin/movie-add.php new file mode 100644 index 000000000..ea35228f3 --- /dev/null +++ b/lib/copy_this/www/admin/movie-add.php @@ -0,0 +1,26 @@ +<?php + +require_once './config.php'; + +$page = new AdminPage(); +$movie = new Movie(); +$id = 0; + +$page->title = "Movie Add"; + +if (isset($_REQUEST['id']) && ctype_digit($_REQUEST['id']) && strlen($_REQUEST['id']) == 7) { + $id = $_REQUEST['id']; + + $movCheck = $movie->getMovieInfo($id); + if (!$movCheck || (isset($_REQUEST['update']) && $_REQUEST['update'] == 1)) + { + if($movie->updateMovieInfo($id)) { + header("Location:".WWW_TOP."/movie-list.php"); + die(); + } + } +} + +$page->content = $page->smarty->fetch('movie-add.tpl'); +$page->render(); + diff --git a/lib/copy_this/www/admin/movie-delete.php b/lib/copy_this/www/admin/movie-delete.php new file mode 100644 index 000000000..26cbd028d --- /dev/null +++ b/lib/copy_this/www/admin/movie-delete.php @@ -0,0 +1,14 @@ +<?php +require_once './config.php'; + +$page = new AdminPage(); + +if (isset($_GET['id'])) +{ + $m = new Movie(); + $m->delete($_GET['id']); +} + +$referrer = $_SERVER['HTTP_REFERER']; +header("Location: " . $referrer); + diff --git a/lib/copy_this/www/admin/movie-edit.php b/lib/copy_this/www/admin/movie-edit.php new file mode 100644 index 000000000..74a06dace --- /dev/null +++ b/lib/copy_this/www/admin/movie-edit.php @@ -0,0 +1,65 @@ +<?php + +require_once './config.php'; + +$page = new AdminPage(); +$movie = new Movie(); +$id = 0; + +// set the current action +$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 'view'; + +if (isset($_REQUEST["id"])) +{ + $id = $_REQUEST["id"]; + $mov = $movie->getMovieInfo($id); + + if (!$mov) { + $page->show404(); + } + + switch($action) + { + case 'submit': + $coverLoc = WWW_DIR."covers/movies/".$id.'-cover.jpg'; + $backdropLoc = WWW_DIR."covers/movies/".$id.'-backdrop.jpg'; + + if($_FILES['cover']['size'] > 0) + { + $tmpName = $_FILES['cover']['tmp_name']; + $file_info = getimagesize($tmpName); + if(!empty($file_info)) + { + move_uploaded_file($_FILES['cover']['tmp_name'], $coverLoc); + } + } + + if($_FILES['backdrop']['size'] > 0) + { + $tmpName = $_FILES['backdrop']['tmp_name']; + $file_info = getimagesize($tmpName); + if(!empty($file_info)) + { + move_uploaded_file($_FILES['backdrop']['tmp_name'], $backdropLoc); + } + } + + $_POST['cover'] = (file_exists($coverLoc)) ? 1 : 0; + $_POST['backdrop'] = (file_exists($backdropLoc)) ? 1 : 0; + + $movie->update($id, $_POST["title"], $_POST['tagline'], $_POST["plot"], $_POST["year"], $_POST["rating"], $_POST["genre"], $_POST["director"], $_POST["actors"], $_POST["language"], $_POST["cover"], $_POST['backdrop']); + + header("Location:".WWW_TOP."/movie-list.php"); + die(); + break; + case 'view': + default: + $page->title = "Movie Edit"; + $page->smarty->assign('movie', $mov); + break; + } +} + +$page->content = $page->smarty->fetch('movie-edit.tpl'); +$page->render(); + diff --git a/lib/copy_this/www/admin/movie-list.php b/lib/copy_this/www/admin/movie-list.php new file mode 100644 index 000000000..1fe07efe7 --- /dev/null +++ b/lib/copy_this/www/admin/movie-list.php @@ -0,0 +1,32 @@ +<?php + +require_once './config.php'; + +$page = new AdminPage(); + +$movie = new Movie(); + +$page->title = "Movie List"; + +$tname = ""; +if (isset($_REQUEST['moviename']) && !empty($_REQUEST['moviename'])) + $tname = $_REQUEST['moviename']; + +$movcount = $movie->getCount($tname); + +$offset = isset($_REQUEST["offset"]) ? $_REQUEST["offset"] : 0; +$tsearch = ($tname != "") ? 'moviename='.$tname.'&' : ''; + +$page->smarty->assign('pagertotalitems',$movcount); +$page->smarty->assign('pageroffset',$offset); +$page->smarty->assign('pageritemsperpage',ITEMS_PER_PAGE); +$page->smarty->assign('pagerquerybase', WWW_TOP."/movie-list.php?".$tsearch."&offset="); +$pager = $page->smarty->fetch("pager.tpl"); +$page->smarty->assign('pager', $pager); + +$movielist = $movie->getRange($offset, ITEMS_PER_PAGE, $tname); +$page->smarty->assign('movielist',$movielist); + +$page->content = $page->smarty->fetch('movie-list.tpl'); +$page->render(); + diff --git a/lib/copy_this/www/admin/music-edit.php b/lib/copy_this/www/admin/music-edit.php new file mode 100644 index 000000000..2adab58e1 --- /dev/null +++ b/lib/copy_this/www/admin/music-edit.php @@ -0,0 +1,57 @@ +<?php + +require_once './config.php'; + +$page = new AdminPage(); +$music = new Music(); +$gen = new Genres(); +$id = 0; + +// set the current action +$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 'view'; + +if (isset($_REQUEST["id"])) +{ + $id = $_REQUEST["id"]; + $mus = $music->getMusicInfo($id); + + if (!$mus) { + $page->show404(); + } + + switch($action) + { + case 'submit': + $coverLoc = WWW_DIR."covers/music/".$id.'.jpg'; + + if($_FILES['cover']['size'] > 0) + { + $tmpName = $_FILES['cover']['tmp_name']; + $file_info = getimagesize($tmpName); + if(!empty($file_info)) + { + move_uploaded_file($_FILES['cover']['tmp_name'], $coverLoc); + } + } + + $_POST['cover'] = (file_exists($coverLoc)) ? 1 : 0; + $_POST['salesrank'] = (empty($_POST['salesrank']) || !ctype_digit($_POST['salesrank'])) ? "null" : $_POST['salesrank']; + $_POST['releasedate'] = (empty($_POST['releasedate']) || !strtotime($_POST['releasedate'])) ? $mus['releasedate'] : date("Y-m-d H:i:s", strtotime($_POST['releasedate'])); + + $music->update($id, $_POST["title"], $_POST['asin'], $_POST['url'], $_POST["salesrank"], $_POST["artist"], $_POST["publisher"], $_POST["releasedate"], $_POST["year"], $_POST["tracks"], $_POST["cover"], $_POST["genre"]); + + header("Location:".WWW_TOP."/music-list.php"); + die(); + break; + case 'view': + default: + $page->title = "Music Edit"; + $page->smarty->assign('music', $mus); + $page->smarty->assign('genres', $gen->getGenres(Genres::MUSIC_TYPE)); + break; + } +} + +$page->content = $page->smarty->fetch('music-edit.tpl'); +$page->render(); + diff --git a/lib/copy_this/www/admin/music-list.php b/lib/copy_this/www/admin/music-list.php new file mode 100644 index 000000000..5380ef43b --- /dev/null +++ b/lib/copy_this/www/admin/music-list.php @@ -0,0 +1,27 @@ +<?php + +require_once './config.php'; + +$page = new AdminPage(); + +$m = new Music(); + +$page->title = "Music List"; + +$mcount = $m->getCount(); + +$offset = isset($_REQUEST["offset"]) ? $_REQUEST["offset"] : 0; +$page->smarty->assign('pagertotalitems',$mcount); +$page->smarty->assign('pageroffset',$offset); +$page->smarty->assign('pageritemsperpage',ITEMS_PER_PAGE); +$page->smarty->assign('pagerquerybase', WWW_TOP."/music-list.php?offset="); +$pager = $page->smarty->fetch("pager.tpl"); +$page->smarty->assign('pager', $pager); + +$musiclist = $m->getRange($offset, ITEMS_PER_PAGE); + +$page->smarty->assign('musiclist',$musiclist); + +$page->content = $page->smarty->fetch('music-list.tpl'); +$page->render(); + diff --git a/lib/copy_this/www/admin/nzb-export.php b/lib/copy_this/www/admin/nzb-export.php new file mode 100644 index 000000000..d3fcb1a07 --- /dev/null +++ b/lib/copy_this/www/admin/nzb-export.php @@ -0,0 +1,67 @@ +<?php +require_once './config.php'; + + +if (\newznab\utility\Utility::isCLI()) { + exit ('This script is only for exporting from the web, use the script in misc/testing' . + PHP_EOL); +} + +$page = new AdminPage(); +$rel = new Releases(['Settings' => $page->settings]); + +if ($page->isPostBack()) { + $retVal = $path = ''; + + $path = $_POST["folder"]; + $postFrom = (isset($_POST["postfrom"]) ? $_POST["postfrom"] : ''); + $postTo = (isset($_POST["postto"]) ? $_POST["postto"] : ''); + $group = ($_POST["group"] === '-1' ? 0 : (int)$_POST["group"]); + $gzip = ($_POST["gzip"] === '1' ? true : false); + + if ($path !== "") { + $NE = new NZBExport([ + 'Browser' => true, 'Settings' => $page->settings, + 'Releases' => $rel + ]); + $retVal = $NE->beginExport( + [ + $path, + $postFrom, + $postTo, + $group, + $gzip + ] + ); + } else { + $retVal = 'Error, a path is required!'; + } + + $page->smarty->assign( + [ + 'folder' => $path, + 'output' => $retVal, + 'fromdate' => $postFrom, + 'todate' => $postTo, + 'group' => $_POST["group"], + 'gzip' => $_POST["gzip"] + ] + ); +} else { + $page->smarty->assign( + [ + 'fromdate' => $rel->getEarliestUsenetPostDate(), + 'todate' => $rel->getLatestUsenetPostDate() + ] + ); +} + +$page->title = "Export Nzbs"; +$page->smarty->assign( + [ + 'gziplist' => [1 => 'True', 0 => 'False'], + 'grouplist' => $rel->getReleasedGroupsForSelect(true) + ] +); +$page->content = $page->smarty->fetch('nzb-export.tpl'); +$page->render(); \ No newline at end of file diff --git a/lib/copy_this/www/admin/nzb-import.php b/lib/copy_this/www/admin/nzb-import.php new file mode 100644 index 000000000..a10458bcb --- /dev/null +++ b/lib/copy_this/www/admin/nzb-import.php @@ -0,0 +1,55 @@ +<?php + +// Check if the user is running from CLI. +if (PHP_SAPI === 'cli') { + exit('This is a web only script, run misc/testing/nzb-import.php instead.'); +} + +require_once './config.php'; +$page = new AdminPage(); + +$filesToProcess = []; +if ($page->isPostBack()) { + + $useNzbName = false; + $deleteNZB = true; + // Get the list of NZB files from php /tmp folder if nzb files were uploaded. + if (isset($_FILES["uploadedfiles"])) { + foreach ($_FILES["uploadedfiles"]["error"] as $key => $error) { + if ($error == UPLOAD_ERR_OK) { + $tmp_name = $_FILES["uploadedfiles"]["tmp_name"][$key]; + $name = $_FILES["uploadedfiles"]["name"][$key]; + $filesToProcess[] = $tmp_name; + } + } + } else { + + // Check if the user wants to use the file name as the release name. + $useNzbName = (isset($_POST['usefilename']) && $_POST["usefilename"] == 'on') ? true : false; + + // Check if the user wants to delete the NZB file when done importing. + $deleteNZB = (isset($_POST['deleteNZB']) && $_POST["deleteNZB"] == 'on') ? true : false; + + // Get the path the user set in the browser if he put one. + $path = (isset($_POST["folder"]) ? $_POST["folder"] : ""); + if (substr($path, strlen($path) - 1) !== DS) { + $path .= DS; + } + + // Get the files from the user specified path. + $filesToProcess = glob($path . "*.nzb"); + } + + if (count($filesToProcess) > 0) { + + // Create a new instance of NZBImport and send it the file locations. + $NZBImport = new NZBImport(['Browser' => true, 'Settings' => $page->settings]); + + $page->smarty->assign('output', + $NZBImport->beginImport($filesToProcess, $useNzbName, $deleteNZB)); + } +} + +$page->title = "Import Nzbs"; +$page->content = $page->smarty->fetch('nzb-import.tpl'); +$page->render(); \ No newline at end of file diff --git a/lib/copy_this/www/admin/opcachestats.php b/lib/copy_this/www/admin/opcachestats.php index 07dc0b37d..62a0cd2c7 100644 --- a/lib/copy_this/www/admin/opcachestats.php +++ b/lib/copy_this/www/admin/opcachestats.php @@ -3,8 +3,8 @@ // #newznab-tmux : Denotes modifications done for newznab-tmux integration. /* #newznab-tmux */ -require_once("config.php"); -require_once(WWW_DIR."/lib/adminpage.php"); +require_once './config.php'; + $page = new AdminPage(); $NNURL = $page->serverurl; /* #newznab-tmux */ diff --git a/lib/copy_this/www/admin/preview-list.php b/lib/copy_this/www/admin/preview-list.php new file mode 100644 index 000000000..b818a53e0 --- /dev/null +++ b/lib/copy_this/www/admin/preview-list.php @@ -0,0 +1,38 @@ +<?php + +require_once './config.php'; + +$page = new AdminPage(); +$releases = new Releases(); +$category = new Category(); +$previewtype = 1; + +$page->title = "Preview List"; + +$previewcat="-1"; +if (isset($_REQUEST["previewcat"])) + $previewcat = $_REQUEST["previewcat"]; + +$catarray = array(); +$catarray[] = $previewcat; + +$releasecount = $releases->getPreviewCount($previewtype, $catarray); + +$offset = isset($_REQUEST["offset"]) ? $_REQUEST["offset"] : 0; +$page->smarty->assign('pagertotalitems',$releasecount); +$page->smarty->assign('pageroffset',$offset); +$page->smarty->assign('pageritemsperpage',ITEMS_PER_PAGE); +$page->smarty->assign('pagerquerybase', WWW_TOP."/preview-list.php?previewcat=".$previewcat."&offset="); +$pager = $page->smarty->fetch("pager.tpl"); +$page->smarty->assign('pager', $pager); + +$parentcatlist = $category->getForMenu(); +$page->smarty->assign('catlist',$parentcatlist); +$page->smarty->assign('previewcat',$previewcat); + +$releaselist = $releases->getPreviewRange($previewtype, $catarray, $offset, ITEMS_PER_PAGE); +$page->smarty->assign('releaselist',$releaselist); + +$page->content = $page->smarty->fetch('preview-list.tpl'); +$page->render(); + diff --git a/lib/copy_this/www/admin/rage-delete.php b/lib/copy_this/www/admin/rage-delete.php new file mode 100644 index 000000000..cb941357c --- /dev/null +++ b/lib/copy_this/www/admin/rage-delete.php @@ -0,0 +1,20 @@ +<?php +require_once './config.php'; + +$page = new AdminPage(); + +if (isset($_GET['id'])) +{ + $tvrage = new TvRage(); + $tvrage->delete($_GET['id']); +} + +if(isset($_GET['from']) && !empty($_GET['from'])) +{ + header("Location:".$_GET['from']); + die(); +} + +$referrer = $_SERVER['HTTP_REFERER']; +header("Location: " . $referrer); +die(); diff --git a/lib/copy_this/www/admin/rage-edit.php b/lib/copy_this/www/admin/rage-edit.php new file mode 100644 index 000000000..9c150d963 --- /dev/null +++ b/lib/copy_this/www/admin/rage-edit.php @@ -0,0 +1,103 @@ +<?php + +require_once './config.php'; + +$page = new AdminPage(); +$tvrage = new TvRage(); +$id = 0; + +// set the current action +$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 'view'; + +switch($action) +{ + case 'update': + $tvrage->refreshRageInfo($_GET["id"]); + + if(isset($_GET['from']) && !empty($_GET['from'])) + { + header("Location:".$_GET['from']); + exit; + } + + header("Location:".WWW_TOP."/rage-edit.php?id=".$_GET["id"]); + exit; + + + case 'submit': + if ($_POST["id"] == "") + { + $imgbytes = ""; + if($_FILES['imagedata']['size'] > 0) + { + $fileName = $_FILES['imagedata']['name']; + $tmpName = $_FILES['imagedata']['tmp_name']; + $fileSize = $_FILES['imagedata']['size']; + $fileType = $_FILES['imagedata']['type']; + + // + // check the uploaded file is actually an image. + // + $file_info = getimagesize($tmpName); + if(!empty($file_info)) + { + $fp = fopen($tmpName, 'r'); + $imgbytes = fread($fp, filesize($tmpName)); + fclose($fp); + } + } + + $tvrage->add($_POST["rageID"], $_POST["releasetitle"], $_POST["description"], $_POST["genre"], $_POST['country'], $imgbytes); + } + else + { + $imgbytes = ""; + if($_FILES['imagedata']['size'] > 0) + { + $fileName = $_FILES['imagedata']['name']; + $tmpName = $_FILES['imagedata']['tmp_name']; + $fileSize = $_FILES['imagedata']['size']; + $fileType = $_FILES['imagedata']['type']; + + // + // check the uploaded file is actually an image. + // + $file_info = getimagesize($tmpName); + if(!empty($file_info)) + { + $fp = fopen($tmpName, 'r'); + $imgbytes = fread($fp, filesize($tmpName)); + fclose($fp); + } + } + + $tvrage->update($_POST["id"], $_POST["rageID"], $_POST["releasetitle"], $_POST["description"], $_POST["genre"], $_POST['country'], $imgbytes); + } + + if(isset($_POST['from']) && !empty($_POST['from'])) + { + header("Location:".$_POST['from']); + exit; + } + + header("Location:".WWW_TOP."/rage-list.php"); + break; + case 'view': + default: + + if (isset($_GET["id"])) + { + $page->title = "Tv Rage Edit"; + $id = $_GET["id"]; + + $rage = $tvrage->getByID($id); + $page->smarty->assign('rage', $rage); + } + + break; +} + +$page->title="Add/Edit TV Rage Show Data"; +$page->content = $page->smarty->fetch('rage-edit.tpl'); +$page->render(); + diff --git a/lib/copy_this/www/admin/rage-list.php b/lib/copy_this/www/admin/rage-list.php new file mode 100644 index 000000000..f64ca3d2c --- /dev/null +++ b/lib/copy_this/www/admin/rage-list.php @@ -0,0 +1,34 @@ +<?php + +require_once './config.php'; + +$page = new AdminPage(); + +$tvrage = new TvRage(); + +$page->title = "TV Rage List"; + +$tname = ""; +if (isset($_REQUEST['ragename']) && !empty($_REQUEST['ragename'])) + $tname = $_REQUEST['ragename']; + +$ragecount = $tvrage->getCount($tname); + +$offset = isset($_REQUEST["offset"]) ? $_REQUEST["offset"] : 0; +$tsearch = ($tname != "") ? 'ragename='.$tname.'&' : ''; + +$page->smarty->assign('pagertotalitems',$ragecount); +$page->smarty->assign('pageroffset',$offset); +$page->smarty->assign('pageritemsperpage',ITEMS_PER_PAGE); +$page->smarty->assign('pagerquerybase', WWW_TOP."/rage-list.php?".$tsearch."&offset="); +$pager = $page->smarty->fetch("pager.tpl"); +$page->smarty->assign('pager', $pager); + +$page->smarty->assign('ragename',$tname); + +$tvragelist = $tvrage->getRange($offset, ITEMS_PER_PAGE, $tname); +$page->smarty->assign('tvragelist',$tvragelist); + +$page->content = $page->smarty->fetch('rage-list.tpl'); +$page->render(); + diff --git a/lib/copy_this/www/admin/rage-remove.php b/lib/copy_this/www/admin/rage-remove.php new file mode 100644 index 000000000..06e4d1903 --- /dev/null +++ b/lib/copy_this/www/admin/rage-remove.php @@ -0,0 +1,17 @@ +<?php + +require_once './config.php'; + +$page = new AdminPage(); + +$releases = new Releases(); +$num = 0; +if (isset($_GET["id"])) + $num = $releases->removeRageIdFromReleases($_GET["id"]); + +$page->smarty->assign('numtv',$num); + +$page->title = "Remove Rage Id from Releases"; +$page->content = $page->smarty->fetch('rage-remove.tpl'); +$page->render(); + diff --git a/lib/copy_this/www/admin/regex-edit.php b/lib/copy_this/www/admin/regex-edit.php new file mode 100644 index 000000000..7826558e1 --- /dev/null +++ b/lib/copy_this/www/admin/regex-edit.php @@ -0,0 +1,62 @@ +<?php + +require_once './config.php'; + +$page = new AdminPage(); +$category = new Category(); +$reg = new ReleaseRegex(); +$id = 0; + +// set the current action +$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 'view'; + +switch($action) +{ + case 'submit': + if ($_POST["id"] == "") + { + $reg->add($_POST); + } + else + { + $ret = $reg->update($_POST); + } + header("Location:".WWW_TOP."/regex-list.php"); + break; + case 'addtest': + if (isset($_GET['regex']) && isset($_GET['groupname'])) { + $r = array('groupname'=>$_GET['groupname'], 'regex'=>$_GET['regex'], 'ordinal'=>'1', 'status'=>'1'); + $page->smarty->assign('regex', $r); + } + break; + case 'view': + default: + + $page->title = "Release Regex Add"; + + if (isset($_GET["id"])) + { + $page->title = "Release Regex Edit"; + $id = $_GET["id"]; + + $r = $reg->getByID($id); + + } + else + { + $r = array(); + $r["status"] = 1; + } + $page->smarty->assign('regex', $r); + + break; +} + +$page->smarty->assign('status_ids', array(Category::STATUS_ACTIVE,Category::STATUS_INACTIVE)); +$page->smarty->assign('status_names', array( 'Yes', 'No')); + +$page->smarty->assign('catlist',$category->getForSelect(true)); + +$page->content = $page->smarty->fetch('regex-edit.tpl'); +$page->render(); + diff --git a/lib/copy_this/www/admin/regex-list.php b/lib/copy_this/www/admin/regex-list.php new file mode 100644 index 000000000..60f5a9cf9 --- /dev/null +++ b/lib/copy_this/www/admin/regex-list.php @@ -0,0 +1,25 @@ +<?php + +require_once './config.php'; + +$page = new AdminPage(); + +$reg = new ReleaseRegex(); + +$page->title = "Release Regex List"; + +$reggrouplist = $reg->getGroupsForSelect(); +$page->smarty->assign('reggrouplist', $reggrouplist); + +$group=".*"; +if (isset($_REQUEST["group"])) + $group = $_REQUEST["group"]; + +$page->smarty->assign('selectedgroup', $group); + +$regexlist = $reg->get(false, $group, true); +$page->smarty->assign('regexlist', $regexlist); + +$page->content = $page->smarty->fetch('regex-list.tpl'); +$page->render(); + diff --git a/lib/copy_this/www/admin/regex-submit.php b/lib/copy_this/www/admin/regex-submit.php new file mode 100644 index 000000000..d0e887b9e --- /dev/null +++ b/lib/copy_this/www/admin/regex-submit.php @@ -0,0 +1,57 @@ +<?php + +require_once './config.php'; + +$page = new AdminPage(); +$page->title = "Submit your regex expressions to newznab"; + +$regex = new ReleaseRegex(); +$regexList = $regex->get(false, -1, true, true); + +if (count($regexList)) +{ + $regexSerialize = serialize($regexList); + $regexFilename = 'releaseregex-' . time() . '.regex'; + + // User wants to submit their regex's + if (isset($_POST['regex_submit_please'])) + { + // Submit + $ch = curl_init(); + curl_setopt($ch, CURLOPT_HEADER, 0); + curl_setopt($ch, CURLOPT_VERBOSE, 0); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (newznab / compatible;)"); + curl_setopt($ch, CURLOPT_URL,"http://newznab.com/regex/uploadregex.php"); + curl_setopt($ch, CURLOPT_POST, true); + $post = array( + "regex" => $regexSerialize + ); + curl_setopt($ch, CURLOPT_POSTFIELDS, $post); + $response = curl_exec($ch); + + curl_close($ch); + + if ($response == 'OK') + { + $page->smarty->assign('upload_status', 'OK'); + } + else + { + $page->smarty->assign('upload_status', 'BAD'); + } + } +} +else +{ + $regexFilename = 'No user regexs found. Please add some.'; + $regexList = array('Empty'); + $page->smarty->assign('regex_error', 1); +} + +$page->smarty->assign('regex_filename', $regexFilename); +$page->smarty->assign('regex_contents', $regexList); + +$page->content = $page->smarty->fetch('regex-submit.tpl'); +$page->render(); + diff --git a/lib/copy_this/www/admin/regex-test.php b/lib/copy_this/www/admin/regex-test.php new file mode 100644 index 000000000..88bf66a79 --- /dev/null +++ b/lib/copy_this/www/admin/regex-test.php @@ -0,0 +1,85 @@ +<?php + +require_once './config.php'; + + +$page = new AdminPage(); +$reg = new ReleaseRegex(); +$groups = new Groups(); +$cat = new Category(); +$id = 0; + +// set the current action +$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 'view'; + +$numarticlesdefault = 20000; +$groupList = $groups->getAll(); +array_unshift($groupList, array('ID'=>0, 'name'=>'All Groups')); + +$gid = $gnames = array(); +$groupname = (isset($_REQUEST['groupname']) && !empty($_REQUEST['groupname'])) ? $_REQUEST['groupname'] : ''; +$groupID = isset($_REQUEST['groupID']) ? $_REQUEST['groupID'] : '0'; +$regex = (isset($_REQUEST['regex']) && !empty($_REQUEST['regex'])) ? $_REQUEST['regex'] : '/^(?P<name>.*)$/i'; +$poster = (isset($_REQUEST['poster']) && !empty($_REQUEST['poster'])) ? $_REQUEST['poster'] : ''; +$unreleased = isset($_REQUEST['unreleased']) ? $_REQUEST['unreleased'] : ''; +$matchagainstbins = isset($_REQUEST['matchagainstbins']) ? $_REQUEST['matchagainstbins'] : ''; +$numarticles = (isset($_REQUEST['numarticles']) && !empty($_REQUEST['numarticles'])) ? $_REQUEST['numarticles'] : $numarticlesdefault; +$clearexistingbins = isset($_REQUEST['clearexistingbins']) ? true : false; +foreach($groupList as $grp) +{ + $gid[$grp["ID"]] = $grp["ID"]; + $gnames[$grp["ID"]] = $grp["name"]; +} + +$group = $groupname; +if ($group == '') +{ + if ($groupID == 0) + $group = 0; + else + $group = $gnames[$groupID]; +} + +$page->smarty->assign('gid', $gid); +$page->smarty->assign('gnames', $gnames); +$page->smarty->assign('group', $group); +$page->smarty->assign('groupname', $groupname); +$page->smarty->assign('groupID', $groupID); +$page->smarty->assign('regex', $regex); +$page->smarty->assign('poster', $poster); +$page->smarty->assign('unreleased', $unreleased); +$page->smarty->assign('matchagainstbins', $matchagainstbins); +$page->smarty->assign('numarticles', $numarticles); + +switch($action) +{ + case 'test': + if (isset($_REQUEST["regex"])) + { + $matches = $reg->testRegex($_REQUEST['regex'], $group, $poster, $unreleased, $matchagainstbins); + + $offset = isset($_REQUEST["offset"]) ? $_REQUEST["offset"] : 0; + $page->smarty->assign('pagertotalitems',sizeof($matches)); + $page->smarty->assign('pageroffset',$offset); + $page->smarty->assign('pageritemsperpage',ITEMS_PER_PAGE); + $page->smarty->assign('pagerquerybase', WWW_TOP."/regex-test.php?action=test&groupname={$groupname}&groupID={$groupID}®ex=".urlencode($regex)."&poster=".urlencode($poster)."&unreleased={$unreleased}&matchagainstbins={$matchagainstbins}&offset="); + $pager = $page->smarty->fetch("pager.tpl"); + $page->smarty->assign('pager', $pager); + + $matches = array_slice($matches, $offset, ITEMS_PER_PAGE); + + $page->smarty->assign('matches', $matches); + } + break; + case 'fetch': + $result = $reg->fetchTestBinaries($group, $numarticles, $clearexistingbins); + + $page->smarty->assign('error', implode('<br />', $result)); + + break; +} + +$page->title = "Release Regex Test"; + +$page->content = $page->smarty->fetch('regex-test.tpl'); +$page->render(); diff --git a/lib/copy_this/www/admin/release-delete.php b/lib/copy_this/www/admin/release-delete.php new file mode 100644 index 000000000..597de1135 --- /dev/null +++ b/lib/copy_this/www/admin/release-delete.php @@ -0,0 +1,17 @@ +<?php +require_once './config.php'; + +$page = new AdminPage(); + +if (isset($_GET['id'])) +{ + $releases = new Releases(); + $releases->delete($_GET['id']); +} + +if (isset($_GET['from'])) + $referrer = $_GET['from']; +else + $referrer = $_SERVER['HTTP_REFERER']; +header("Location: " . $referrer); + diff --git a/lib/copy_this/www/admin/release-edit.php b/lib/copy_this/www/admin/release-edit.php index 70c2d8273..dc388d4ad 100644 --- a/lib/copy_this/www/admin/release-edit.php +++ b/lib/copy_this/www/admin/release-edit.php @@ -1,9 +1,6 @@ <?php -require_once("config.php"); -require_once(WWW_DIR."/lib/adminpage.php"); -require_once(WWW_DIR."/lib/releases.php"); -require_once(WWW_DIR."/lib/category.php"); +require_once './config.php'; $page = new AdminPage(); $releases = new Releases(); @@ -39,7 +36,6 @@ switch($action) if ($release && $release["imdbid"] != "") { - require_once(WWW_DIR."/lib/movie.php"); $movie = new Movie(); $mov = $movie->getMovieInfo($release['imdbid']); $page->smarty->assign('updatename', $mov["title"]); @@ -47,7 +43,6 @@ switch($action) if ($release && $release["musicinfoid"] != "") { - require_once(WWW_DIR."/lib/music.php"); $music = new Music(); $mus = $music->getMusicInfo($release['musicinfoid']); $page->smarty->assign('updatename', $mus["artist"]." - ".$mus["title"].($mus["year"] != "" ? " - ".$mus["year"] : "")); diff --git a/lib/copy_this/www/admin/release-files.php b/lib/copy_this/www/admin/release-files.php new file mode 100644 index 000000000..a20b59ffd --- /dev/null +++ b/lib/copy_this/www/admin/release-files.php @@ -0,0 +1,42 @@ +<?php + +require_once './config.php'; + +$page = new AdminPage; +$users = new Users; +$releases = new Releases; +$nzb = new Nzb; + +if (!$users->isLoggedIn()) + $page->show403(); + +if (isset($_GET["id"])) +{ + $rel = $releases->getByGuid($_GET["id"]); + if (!$rel) + $page->show404(); + + $nzbpath = $nzb->getNZBPath($_GET["id"], $page->site->nzbpath); + + if (!file_exists($nzbpath)) + $page->show404(); + + ob_start(); + @readgzfile($nzbpath); + $nzbfile = ob_get_contents(); + ob_end_clean(); + + $ret = $nzb->nzbFileList($nzbfile); + + $page->smarty->assign('rel', $rel); + $page->smarty->assign('files', $ret); + + $page->title = "File List"; + $page->meta_title = "View Nzb file list"; + $page->meta_keywords = "view,nzb,file,list,description,details"; + $page->meta_description = "View Nzb File List"; + + $page->content = $page->smarty->fetch('release-files.tpl'); + $page->render(); +} + diff --git a/lib/copy_this/www/admin/release-list.php b/lib/copy_this/www/admin/release-list.php new file mode 100644 index 000000000..279ca794d --- /dev/null +++ b/lib/copy_this/www/admin/release-list.php @@ -0,0 +1,26 @@ +<?php + +require_once './config.php'; + +$page = new AdminPage(); + +$releases = new Releases(); + +$page->title = "Release List"; + +$releasecount = $releases->getCount(); + +$offset = isset($_REQUEST["offset"]) ? $_REQUEST["offset"] : 0; +$page->smarty->assign('pagertotalitems',$releasecount); +$page->smarty->assign('pageroffset',$offset); +$page->smarty->assign('pageritemsperpage',ITEMS_PER_PAGE); +$page->smarty->assign('pagerquerybase', WWW_TOP."/release-list.php?offset="); +$pager = $page->smarty->fetch("pager.tpl"); +$page->smarty->assign('pager', $pager); + +$releaselist = $releases->getRange($offset, ITEMS_PER_PAGE); +$page->smarty->assign('releaselist',$releaselist); + +$page->content = $page->smarty->fetch('release-list.tpl'); +$page->render(); + diff --git a/lib/copy_this/www/admin/release_naming_regexes-edit.php b/lib/copy_this/www/admin/release_naming_regexes-edit.php index 4d2880ce4..a61dc8fde 100644 --- a/lib/copy_this/www/admin/release_naming_regexes-edit.php +++ b/lib/copy_this/www/admin/release_naming_regexes-edit.php @@ -1,7 +1,5 @@ <?php -require_once 'config.php'; -require_once(WWW_DIR."/lib/adminpage.php"); -require_once(WWW_DIR."/lib/Regexes.php"); +require_once './config.php'; $page = new AdminPage(); $regexes = new Regexes(['Settings' => $page->settings, 'Table_Name' => 'release_naming_regexes']); diff --git a/lib/copy_this/www/admin/release_naming_regexes-list.php b/lib/copy_this/www/admin/release_naming_regexes-list.php index 0be7a5419..be1dda3ed 100644 --- a/lib/copy_this/www/admin/release_naming_regexes-list.php +++ b/lib/copy_this/www/admin/release_naming_regexes-list.php @@ -1,7 +1,5 @@ <?php -require_once 'config.php'; -require_once(WWW_DIR."/lib/adminpage.php"); -require_once(WWW_DIR."/lib/Regexes.php"); +require_once './config.php'; $page = new AdminPage(); $regexes = new Regexes(['Settings' => $page->settings, 'Table_Name' => 'release_naming_regexes']); diff --git a/lib/copy_this/www/admin/release_naming_regexes-test.php b/lib/copy_this/www/admin/release_naming_regexes-test.php index 3611f6eb4..fc0325bdc 100644 --- a/lib/copy_this/www/admin/release_naming_regexes-test.php +++ b/lib/copy_this/www/admin/release_naming_regexes-test.php @@ -1,7 +1,5 @@ <?php -require_once 'config.php'; -require_once(WWW_DIR."/lib/adminpage.php"); -require_once(WWW_DIR."/lib/Regexes.php"); +require_once './config.php'; $page = new AdminPage(); diff --git a/lib/copy_this/www/admin/role-delete.php b/lib/copy_this/www/admin/role-delete.php new file mode 100644 index 000000000..1421df714 --- /dev/null +++ b/lib/copy_this/www/admin/role-delete.php @@ -0,0 +1,14 @@ +<?php +require_once './config.php'; + +$page = new AdminPage(); + +if (isset($_GET['id'])) +{ + $users = new Users(); + $users->deleteRole($_GET['id']); +} + +$referrer = $_SERVER['HTTP_REFERER']; +header("Location: " . $referrer); + diff --git a/lib/copy_this/www/admin/role-edit.php b/lib/copy_this/www/admin/role-edit.php new file mode 100644 index 000000000..49cb02fe8 --- /dev/null +++ b/lib/copy_this/www/admin/role-edit.php @@ -0,0 +1,77 @@ +<?php + +require_once './config.php'; + +$page = new AdminPage(); +$users = new Users(); +$category = new Category(); +$id = 0; + +// set the current action +$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 'view'; + +//get the user roles +$userroles = $users->getRoles(); +$roles = array(); +foreach ($userroles as $r) { + $roles[$r['ID']] = $r['name']; +} + +switch($action) +{ + case 'add': + $page->title = "User Roles Add"; + $role = array(); + $role["name"] = ''; + $role["apirequests"] = ''; + $role["downloadrequests"] = ''; + $role["defaultinvites"] = ''; + $role["canpreview"] = 0; + $role["canpre"] = 0; + $role["hideads"] = 0; + $page->smarty->assign('role', $role); + + break; + case 'submit': + if ($_POST["id"] == "") + { + $ret = $users->addRole($_POST['name'], $_POST['apirequests'], $_POST['downloadrequests'], $_POST['defaultinvites'], $_POST['canpreview'], $_POST['canpre'], $_POST['hidetads']); + header("Location:".WWW_TOP."/role-list.php"); + } + else + { + $ret = $users->updateRole($_POST['id'], $_POST['name'], $_POST['apirequests'], $_POST['downloadrequests'], $_POST['defaultinvites'], $_POST['isdefault'], $_POST['canpreview'], $_POST['canpre'], $_POST['hidetads']); + header("Location:".WWW_TOP."/role-list.php"); + + $_POST['exccat'] = (!isset($_POST['exccat']) || !is_array($_POST['exccat'])) ? array() : $_POST['exccat']; + $users->addRoleCategoryExclusions($_POST['id'], $_POST['exccat']); + } + + break; + case 'view': + default: + + if (isset($_GET["id"])) + { + $page->title = "User Roles Edit"; + $id = $_GET["id"]; + $role = $users->getRoleByID($id); + + $page->smarty->assign('role', $role); + } + + break; +} + +$page->smarty->assign('yesno_ids', array(1,0)); +$page->smarty->assign('yesno_names', array( 'Yes', 'No')); + +$page->smarty->assign('catlist',$category->getForSelect(false)); + +if (isset($_GET["id"])) +{ + $page->smarty->assign('roleexccat', $users->getRoleCategoryExclusion($_GET["id"])); +} +$page->content = $page->smarty->fetch('role-edit.tpl'); +$page->render(); + diff --git a/lib/copy_this/www/admin/role-list.php b/lib/copy_this/www/admin/role-list.php new file mode 100644 index 000000000..2807a4858 --- /dev/null +++ b/lib/copy_this/www/admin/role-list.php @@ -0,0 +1,18 @@ +<?php + +require_once './config.php'; + +$page = new AdminPage(); + +$users = new Users(); + +$page->title = "User Role List"; + +//get the user roles +$userroles = $users->getRoles(); + +$page->smarty->assign('userroles',$userroles); + +$page->content = $page->smarty->fetch('role-list.tpl'); +$page->render(); + diff --git a/lib/copy_this/www/admin/sharing.php b/lib/copy_this/www/admin/sharing.php index 7dee3a966..c96368281 100644 --- a/lib/copy_this/www/admin/sharing.php +++ b/lib/copy_this/www/admin/sharing.php @@ -1,7 +1,7 @@ <?php -require_once("config.php"); -require_once(WWW_DIR."/lib/adminpage.php"); -require_once(WWW_DIR."/lib/framework/db.php"); +require_once './config.php'; + +use newznab\db\DB; $page = new AdminPage(); $page->title = 'Sharing Settings'; diff --git a/lib/copy_this/www/admin/site-debug.php b/lib/copy_this/www/admin/site-debug.php index 3bad6f363..9830b7f42 100644 --- a/lib/copy_this/www/admin/site-debug.php +++ b/lib/copy_this/www/admin/site-debug.php @@ -1,7 +1,6 @@ <?php -require_once("config.php"); -require_once(WWW_DIR."/lib/adminpage.php"); +require_once './config.php'; $page = new AdminPage(); @@ -19,7 +18,7 @@ unset($s->sabapikey); unset($s->sabcompletedir); unset($s->sabvdir); -$db = new DB; +$db = new newznab\db\DB; $totalsize = 0; $alltables = $db->query("show table status"); foreach ($alltables as $tablename) diff --git a/lib/copy_this/www/admin/site-edit.php b/lib/copy_this/www/admin/site-edit.php index f88b4336b..53bd4ee2e 100644 --- a/lib/copy_this/www/admin/site-edit.php +++ b/lib/copy_this/www/admin/site-edit.php @@ -1,9 +1,6 @@ <?php -require_once("config.php"); -require_once(WWW_DIR."/lib/adminpage.php"); -require_once(WWW_DIR."/lib/site.php"); -require_once(WWW_DIR."/lib/sabnzbd.php"); +require_once './config.php'; $page = new AdminPage(); $sites = new Sites(); diff --git a/lib/copy_this/www/admin/site-stats.php b/lib/copy_this/www/admin/site-stats.php new file mode 100644 index 000000000..66a460b7f --- /dev/null +++ b/lib/copy_this/www/admin/site-stats.php @@ -0,0 +1,37 @@ +<?php + +require_once './config.php'; + +$page = new AdminPage(); +$users = new Users(); +$releases = new Releases(); + +$page->title = "Site Stats"; + +$topgrabs = $users->getTopGrabbers(); +$page->smarty->assign('topgrabs', $topgrabs); + +$topdownloads = $releases->getTopDownloads(); +$page->smarty->assign('topdownloads', $topdownloads); + +$topcomments = $releases->getTopComments(); +$page->smarty->assign('topcomments', $topcomments); + +$recent = $releases->getRecentlyAdded(); +$page->smarty->assign('recent', $recent); + +$usersbymonth = $users->getUsersByMonth(); +$page->smarty->assign('usersbymonth', $usersbymonth); + +$usersbyrole = $users->getUsersByRole(); +$page->smarty->assign('usersbyrole', $usersbyrole); + +$usersbyhosthash = $users->getUsersByHostHash(); +$page->smarty->assign('usersbyhosthash', $usersbyhosthash); + +$loginsbymonth = $users->getLoginCountsByMonth(); +$page->smarty->assign('loginsbymonth', $loginsbymonth); + +$page->content = $page->smarty->fetch('site-stats.tpl'); +$page->render(); + diff --git a/lib/copy_this/www/admin/spotnab-delete.php b/lib/copy_this/www/admin/spotnab-delete.php new file mode 100644 index 000000000..fed5c2acd --- /dev/null +++ b/lib/copy_this/www/admin/spotnab-delete.php @@ -0,0 +1,14 @@ +<?php +require_once './config.php'; + +$page = new AdminPage(); + +if (isset($_GET['id'])) +{ + $spotnab = new Spotnab(); + $spotnab->deleteSource($_GET['id']); +} + +$referrer = $_SERVER['HTTP_REFERER']; +header("Location: " . $referrer); + diff --git a/lib/copy_this/www/admin/spotnab-edit.php b/lib/copy_this/www/admin/spotnab-edit.php new file mode 100644 index 000000000..47f266b3e --- /dev/null +++ b/lib/copy_this/www/admin/spotnab-edit.php @@ -0,0 +1,55 @@ +<?php + +require_once './config.php'; + +$page = new AdminPage(); +$spotnab = new Spotnab(); +$id = 0; + +// set the current action +$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 'view'; + +switch($action) +{ + case 'add': + $page->title = "Spotnab Source Add"; + $source = array(); + $source["description"] = ''; + $row = $spotnab->getDefaultValue('spotnabsources','username'); + $source["username"] = $row[0]["Default"]; + $row = $spotnab->getDefaultValue('spotnabsources','useremail'); + $source["useremail"] = $row[0]["Default"]; + $row = $spotnab->getDefaultValue('spotnabsources','usenetgroup'); + $source["usenetgroup"] = $row[0]["Default"]; + $source["publickey"] = ''; + $page->smarty->assign('source', $source); + break; + case 'submit': + if ($_POST["id"] == "") + { + $ret = $spotnab->addSource($_POST['description'], $_POST['username'], $_POST['useremail'], $_POST['usenetgroup'], $_POST['publickey']); + header("Location:".WWW_TOP."/spotnab-list.php"); + } + else + { + $ret = $spotnab->updateSource($_POST['id'],$_POST['description'], $_POST['username'], $_POST['useremail'], $_POST['usenetgroup'], $_POST['publickey']); + header("Location:".WWW_TOP."/spotnab-list.php"); + } + break; + case 'view': + default: + + if (isset($_GET["id"])) + { + $page->title = "Spotnab Source Edit"; + $id = $_GET["id"]; + $source = $spotnab->getSourceByID($id); + $page->smarty->assign('source', $source); + } + + break; +} + +$page->content = $page->smarty->fetch('spotnab-edit.tpl'); +$page->render(); + diff --git a/lib/copy_this/www/admin/spotnab-list.php b/lib/copy_this/www/admin/spotnab-list.php new file mode 100644 index 000000000..f5f550d98 --- /dev/null +++ b/lib/copy_this/www/admin/spotnab-list.php @@ -0,0 +1,23 @@ +<?php + +require_once './config.php'; + +$page = new AdminPage(); + +$spotnab = new Spotnab(); + +// set the current action +$toggle = isset($_REQUEST['toggle']) ? $_REQUEST['toggle'] : 'view'; + +if ( (isset($_GET["toggle"])) && (isset($_GET["id"])) ) { + $spotnab->toggleSource($_GET["id"],$_GET["toggle"]); +} + +$page->title = "Spotnab Sources List"; + +//get the list of Sources +$spotnab = $spotnab->getSources(); + +$page->smarty->assign('spotnab',$spotnab); +$page->content = $page->smarty->fetch('spotnab-list.tpl'); +$page->render(); diff --git a/lib/copy_this/www/admin/thetvdb-delete.php b/lib/copy_this/www/admin/thetvdb-delete.php new file mode 100644 index 000000000..ea314b8af --- /dev/null +++ b/lib/copy_this/www/admin/thetvdb-delete.php @@ -0,0 +1,14 @@ +<?php +require_once './config.php'; + +$page = new AdminPage(); + +if (isset($_GET['id'])) +{ + $TheTVDB = new TheTVDB(); + $TheTVDB->deleteTitle($_GET['id']); +} + +$referrer = $_SERVER['HTTP_REFERER']; +header("Location: " . $referrer); + diff --git a/lib/copy_this/www/admin/thetvdb-edit.php b/lib/copy_this/www/admin/thetvdb-edit.php new file mode 100644 index 000000000..49a7d33b1 --- /dev/null +++ b/lib/copy_this/www/admin/thetvdb-edit.php @@ -0,0 +1,42 @@ +<?php + +require_once './config.php'; + +$page = new AdminPage(); +$TheTVDB = new TheTVDB(); +$id = 0; + +// set the current action +$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 'view'; + +switch($action) +{ + case 'submit': + + $TheTVDB->updateSeries($_POST['tvdbID'], $_POST['actors'], $_POST['airsday'], $_POST['airstime'], $_POST['contentrating'], $_POST['firstaired'], $_POST['genre'], $_POST['imdbID'], $_POST['network'], $_POST['overview'], $_POST['rating'], $_POST['ratingcount'], $_POST['runtime'], $_POST['seriesname'], $_POST['status']); + + if(isset($_POST['from']) && !empty($_POST['from'])) + { + header("Location:".$_POST['from']); + exit; + } + + header("Location:".WWW_TOP."/thetvdb-list.php"); + break; + + case 'view': + default: + + if (isset($_GET["id"])) + { + $page->title = "TheTVDB Edit"; + $page->smarty->assign('series', $TheTVDB->getSeriesInfoByID($_GET["id"])); + } + + break; +} + +$page->title="Edit TheTVDB Data"; +$page->content = $page->smarty->fetch('thetvdb-edit.tpl'); +$page->render(); + diff --git a/lib/copy_this/www/admin/thetvdb-list.php b/lib/copy_this/www/admin/thetvdb-list.php new file mode 100644 index 000000000..5c53f3ab3 --- /dev/null +++ b/lib/copy_this/www/admin/thetvdb-list.php @@ -0,0 +1,34 @@ +<?php + +require_once './config.php'; + +$page = new AdminPage(); + +$TheTVDB = new TheTVDB(); + +$page->title = "TheTVDB List"; + +$sname = ""; +if (isset($_REQUEST['seriesname']) && !empty($_REQUEST['seriesname'])) + $sname = $_REQUEST['seriesname']; + +$seriescount = $TheTVDB->getSeriesCount($sname); + +$offset = isset($_REQUEST["offset"]) ? $_REQUEST["offset"] : 0; +$ssearch = ($sname != "") ? 'seriesname='.$sname.'&' : ''; + +$page->smarty->assign('pagertotalitems',$seriescount); +$page->smarty->assign('pageroffset',$offset); +$page->smarty->assign('pageritemsperpage',ITEMS_PER_PAGE); +$page->smarty->assign('pagerquerybase', WWW_TOP."/thetvdb-list.php?".$ssearch."&offset="); +$pager = $page->smarty->fetch("pager.tpl"); +$page->smarty->assign('pager', $pager); + +$page->smarty->assign('seriesname',$sname); + +$serieslist = $TheTVDB->getSeriesRange($offset, ITEMS_PER_PAGE, $sname); +$page->smarty->assign('serieslist',$serieslist); + +$page->content = $page->smarty->fetch('thetvdb-list.tpl'); +$page->render(); + diff --git a/lib/copy_this/www/admin/thetvdb-remove.php b/lib/copy_this/www/admin/thetvdb-remove.php new file mode 100644 index 000000000..dc38c1e75 --- /dev/null +++ b/lib/copy_this/www/admin/thetvdb-remove.php @@ -0,0 +1,15 @@ +<?php + +require_once './config.php'; + +$page = new AdminPage(); + +$releases = new Releases(); +$num = (isset($_GET["id"])) ? $releases->removeThetvdbIdFromReleases($_GET["id"]) : 0; + +$page->smarty->assign('numtv',$num); + +$page->title = "Remove tvdbID from Releases"; +$page->content = $page->smarty->fetch('thetvdb-remove.tpl'); +$page->render(); + diff --git a/lib/copy_this/www/admin/tmux-edit.php b/lib/copy_this/www/admin/tmux-edit.php index cbee5b490..54cecb0e9 100644 --- a/lib/copy_this/www/admin/tmux-edit.php +++ b/lib/copy_this/www/admin/tmux-edit.php @@ -1,7 +1,5 @@ <?php -require_once("config.php"); -require_once(WWW_DIR."/lib/adminpage.php"); -require_once(WWW_DIR."/lib/Tmux.php"); +require_once './config.php'; $page = new AdminPage(); $tmux = new Tmux(); diff --git a/lib/copy_this/www/admin/user-delete.php b/lib/copy_this/www/admin/user-delete.php new file mode 100644 index 000000000..16314faaa --- /dev/null +++ b/lib/copy_this/www/admin/user-delete.php @@ -0,0 +1,20 @@ +<?php +require_once './config.php'; + +$page = new AdminPage(); + +if (isset($_GET['id'])) +{ + $users = new Users(); + $users->delete($_GET['id']); +} + +if (isset($_GET['redir'])) +{ + header("Location: " . $_GET['redir']); +} +else +{ + $referrer = $_SERVER['HTTP_REFERER']; + header("Location: " . $referrer); +} diff --git a/lib/copy_this/www/admin/user-edit.php b/lib/copy_this/www/admin/user-edit.php index cd150367b..41dd255b0 100644 --- a/lib/copy_this/www/admin/user-edit.php +++ b/lib/copy_this/www/admin/user-edit.php @@ -1,8 +1,6 @@ <?php -require_once("config.php"); -require_once(WWW_DIR . "/lib/adminpage.php"); -require_once(WWW_DIR . "/lib/users.php"); +require_once './config.php'; $page = new AdminPage(); $users = new Users(); diff --git a/lib/copy_this/www/admin/user-list.php b/lib/copy_this/www/admin/user-list.php index e658b0919..7e4b1d331 100644 --- a/lib/copy_this/www/admin/user-list.php +++ b/lib/copy_this/www/admin/user-list.php @@ -1,8 +1,6 @@ <?php -require_once("config.php"); -require_once(WWW_DIR."/lib/adminpage.php"); -require_once(WWW_DIR."/lib/users.php"); +require_once './config.php'; $page = new AdminPage(); diff --git a/lib/copy_this/www/admin/view-logs.php b/lib/copy_this/www/admin/view-logs.php index b783debb5..ec94ece0f 100644 --- a/lib/copy_this/www/admin/view-logs.php +++ b/lib/copy_this/www/admin/view-logs.php @@ -1,8 +1,6 @@ <?php -require_once("config.php"); -require_once(WWW_DIR . "/lib/adminpage.php"); -require_once(WWW_DIR . "/lib/Logger.php"); +require_once './config.php'; $page = new AdminPage(); $page->title = 'View Logs'; diff --git a/lib/copy_this/www/automated.config.php b/lib/copy_this/www/automated.config.php index 4b0c20fa6..e31b677a2 100644 --- a/lib/copy_this/www/automated.config.php +++ b/lib/copy_this/www/automated.config.php @@ -7,17 +7,20 @@ define('NN_MINIMUM_MYSQL_VERSION', '5.5'); define('DS', DIRECTORY_SEPARATOR); // These are file path constants -define('NN_ROOT', realpath((dirname(__FILE__))) . DS); +define('NN_ROOT', realpath(dirname(dirname(__FILE__))) . DS); // Used to refer to the main lib class files. -define('NN_LIB', NN_ROOT . 'lib' . DS); +define('NN_LIB', NN_ROOT . 'newznab' . DS); define('NN_CORE', NN_LIB); +// Used to refer to the third party library files. +define('NN_LIBS', NN_ROOT . 'libs' . DS); + // Refers to the web root for the Smarty lib -define('NN_WWW', NN_ROOT); +define('NN_WWW', NN_ROOT . 'www' . DS); //Refers to the misc folder -define('NN_MISC', NN_WWW . '..' . DS . 'misc' . DS); +define('NN_MISC', NN_ROOT . 'misc' . DS); //Refers to update_scripts folder define('NN_UPDATE', NN_MISC . 'update_scripts' . DS); @@ -52,7 +55,7 @@ if (function_exists('ini_set') && function_exists('ini_get')) { } // Path to smarty files. (not prefixed with NN as the name is needed in smarty files). -define('SMARTY_DIR', NN_LIB . 'smarty' . DS); +define('SMARTY_DIR', NN_LIBS . 'smarty' . DS); // // used to refer to the /www/lib class files @@ -73,13 +76,12 @@ define('NN_VERSIONS', NN_LIB . 'build' . DS . 'newznab.xml'); if (is_file(__DIR__ . DS . 'settings.php')) { require_once(__DIR__ . DS . 'settings.php'); // Remove this in the future, here for those not updating settings.php - if (!defined('NN_USE_SQL_TRANSACTIONS')) { - define('NN_USE_SQL_TRANSACTIONS', true); + if (!defined('NN_MAX_PAGER_RESULTS')) { + define('NN_MAX_PAGER_RESULTS', '125000'); } } else { define('ITEMS_PER_PAGE', '50'); define('ITEMS_PER_COVER_PAGE', '20'); - define('ITEMS_PER_PAGE_SMALL', '15'); define('NN_ECHOCLI', true); define('NN_DEBUG', false); define('NN_LOGGING', false); @@ -89,19 +91,26 @@ if (is_file(__DIR__ . DS . 'settings.php')) { define('NN_LOGERROR', false); define('NN_LOGFATAL', false); define('NN_LOGQUERIES', false); + define('NN_LOGAUTOLOADER', false); define('NN_QUERY_STRIP_WHITESPACE', false); define('NN_RENAME_PAR2', true); define('NN_RENAME_MUSIC_MEDIAINFO', true); define('NN_CACHE_EXPIRY_SHORT', 300); define('NN_CACHE_EXPIRY_MEDIUM', 600); define('NN_CACHE_EXPIRY_LONG', 900); + define('NN_PREINFO_OPEN', false); define('NN_FLOOD_CHECK', false); define('NN_FLOOD_WAIT_TIME', 5); define('NN_FLOOD_MAX_REQUESTS_PER_SECOND', 5); define('NN_USE_SQL_TRANSACTIONS', true); + define('NN_RELEASE_SEARCH_TYPE', 0); + define('NN_MAX_PAGER_RESULTS', '125000'); } -require_once(WWW_DIR . "/lib/util.php"); -define('HAS_WHICH', Utility::hasWhich() ? true : false); +require_once NN_CORE . 'autoloader.php'; +require_once NN_LIBS . 'autoloader.php'; +require_once SMARTY_DIR . 'autoloader.php'; + +define('HAS_WHICH', newznab\utility\Utility::hasWhich() ? true : false); if (file_exists(__DIR__ . DS . 'config.php')) { require_once __DIR__ . DS . 'config.php'; diff --git a/lib/copy_this/www/index.php b/lib/copy_this/www/index.php new file mode 100644 index 000000000..f6e6e2a0d --- /dev/null +++ b/lib/copy_this/www/index.php @@ -0,0 +1,21 @@ +<?php +if(is_file("config.php")) { + require_once("config.php"); +} else { + if(is_dir("install")) { + header("location: install"); + exit(); + } +} + +require_once 'automated.config.php'; + +$page = new Page; +$users = new Users; + +if ($page->site->style != "default" && file_exists(NN_WWW.'pages/'.$page->site->style."/".$page->page.'.php')) + include(NN_WWW.'pages/'.$page->site->style."/".$page->page.'.php'); +elseif (file_exists(WWW_DIR.'pages/'.$page->page.'.php')) + include(NN_WWW.'pages/'.$page->page.'.php'); +else + $page->show404(); diff --git a/lib/copy_this/www/install/config.php.tpl b/lib/copy_this/www/install/config.php.tpl new file mode 100644 index 000000000..aa085b0ed --- /dev/null +++ b/lib/copy_this/www/install/config.php.tpl @@ -0,0 +1,42 @@ +<?php + +//========================= +// Config you must change - updated by installer. +//========================= +define('DB_SYSTEM', '%%DB_SYSTEM%%'); +define('DB_HOST', '%%DB_HOST%%'); +define('DB_PORT', '%%DB_PORT%%'); +define('DB_SOCKET', '%%DB_SOCKET%%'); +define('DB_USER', '%%DB_USER%%'); +define('DB_PASSWORD', '%%DB_PASSWORD%%'); +define('DB_NAME', '%%DB_NAME%%'); +define('DB_PCONNECT', false); + +define('NNTP_USERNAME', '%%NNTP_USERNAME%%'); +define('NNTP_PASSWORD', '%%NNTP_PASSWORD%%'); +define('NNTP_SERVER', '%%NNTP_SERVER%%'); +define('NNTP_PORT', '%%NNTP_PORT%%'); +// If you want to use TLS or SSL on the NNTP connection (the NNTP_PORT must be able to support encryption). +define('NNTP_SSLENABLED', %%NNTP_SSLENABLED%%); +// If we lose connection to the NNTP server, this is the time in seconds to wait before giving up. +define('NNTP_SOCKET_TIMEOUT', '%%NNTP_SOCKET_TIMEOUT%%'); + +define('NNTP_USERNAME_A', '%%NNTP_USERNAME_A%%'); +define('NNTP_PASSWORD_A', '%%NNTP_PASSWORD_A%%'); +define('NNTP_SERVER_A', '%%NNTP_SERVER_A%%'); +define('NNTP_PORT_A', '%%NNTP_PORT_A%%'); +define('NNTP_SSLENABLED_A', %%NNTP_SSLENABLED_A%%); +define('NNTP_SOCKET_TIMEOUT_A', '%%NNTP_SOCKET_TIMEOUT_A%%'); + +// Location to CA bundle file on your system. You can download one here: http://curl.haxx.se/docs/caextract.html +define('NN_SSL_CAFILE', '%%NN_SSL_CAFILE%%'); +// Path where openssl cert files are stored on your system, this is a fall back if the CAFILE is not found. +define('NN_SSL_CAPATH', '%%NN_SSL_CAPATH%%'); +// Use the aforementioned CA bundle file to verify remote SSL certificates when connecting to a server using TLS/SSL. +define('NN_SSL_VERIFY_PEER', '%%NN_SSL_VERIFY_PEER%%'); +// Verify the host is who they say they are. +define('NN_SSL_VERIFY_HOST', '%%NN_SSL_VERIFY_HOST%%'); +// Allow self signed certificates. Note this does not work on CURL as CURL does not have this option. +define('NN_SSL_ALLOW_SELF_SIGNED', '%%NN_SSL_ALLOW_SELF_SIGNED%%'); + +require_once 'automated.config.php'; \ No newline at end of file diff --git a/lib/copy_this/www/install/index.php b/lib/copy_this/www/install/index.php new file mode 100644 index 000000000..1f345b479 --- /dev/null +++ b/lib/copy_this/www/install/index.php @@ -0,0 +1,67 @@ +<?php +@session_start(); +require_once realpath(__DIR__ . '/../automated.config.php'); +$page_title = "Welcome"; + +$cfg = new Install(); +if ($cfg->isLocked()) { + $cfg->error = true; +} + +$cfg->cacheCheck = is_writable($cfg->SMARTY_DIR.'/templates_c'); +if ($cfg->cacheCheck === false) { $cfg->error = true; } + +if (!$cfg->error) { + $cfg->setSession(); +} + +?> +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml"> +<head> + <meta http-equiv="content-type" content="text/html; charset=utf-8" /> + <title><?php echo $page_title; ?> + + + + +

Newznab

+
+ + diff --git a/lib/copy_this/www/install/step1.php b/lib/copy_this/www/install/step1.php new file mode 100644 index 000000000..c49d6e035 --- /dev/null +++ b/lib/copy_this/www/install/step1.php @@ -0,0 +1,194 @@ +title = "Preflight Checklist"; + +$cfg = new Install(); + +if (!$cfg->isInitialized()) { + header("Location: index.php"); + die(); +} + +$cfg->setSession(); +$cfg = $cfg->getSession(); + +// Start checks. +$cfg->sessionsPathPermissions = true; +$sessionPath = session_save_path(); +$sessionPath = empty($sessionPath) ? sys_get_temp_dir() : $sessionPath; +$page->smarty->assign('sessionsSavePath', $sessionPath); +if (!is_readable($sessionPath) || !is_writable($sessionPath)) { + $cfg->error = true; + $cfg->sessionsPathPermissions = false; +} + +$cfg->cryptCheck = function_exists('crypt'); +if ($cfg->cryptCheck === false) { + $cfg->error = true; +} + +$cfg->sha1Check = function_exists('sha1'); +if ($cfg->sha1Check === false) { + $cfg->error = true; +} + +$cfg->PDOCheck = extension_loaded('PDO'); +if ($cfg->PDOCheck === false) { + $cfg->error = true; +} + +$cfg->jsonCheck = extension_loaded('json'); +if ($cfg->jsonCheck === false) { + $cfg->error = true; +} + +$cfg->gdCheck = function_exists('imagecreatetruecolor'); + +$cfg->curlCheck = function_exists('curl_init'); + +if (extension_loaded('posix') && strtolower(substr(PHP_OS, 0, 3)) !== 'win') { + $group = posix_getgrgid(posix_getgid()); + $fixString = '

Another solution is to run:
chown -R YourUnixUserName:' . $group['name'] . ' ' . NN_ROOT . + '
Then give your user access to the group:
usermod -a -G ' . $group['name'] . ' YourUnixUserName' . + '
Finally give read/write access to your user/group:
chmod -R 774 ' . NN_ROOT; + $page->smarty->assign('fixString', $fixString); + $page->smarty->assign('unixGroup', $group['name']); + $page->smarty->assign('rootPath', NN_ROOT); +} else { + $page->smarty->assign('fixString', false); +} + +$cfg->cacheCheck = is_writable(SMARTY_DIR . 'templates_c'); +if ($cfg->cacheCheck === false) { + $cfg->error = true; +} + +$cfg->animeCoversCheck = is_writable($cfg->COVERS_PATH . 'anime'); +if ($cfg->animeCoversCheck === false) { + $cfg->error = true; +} + +$cfg->audioCoversCheck = is_writable($cfg->COVERS_PATH . 'audio'); +if ($cfg->audioCoversCheck === false) { + $cfg->error = true; +} + +$cfg->audiosampleCoversCheck = is_writable($cfg->COVERS_PATH . 'audiosample'); +if ($cfg->audiosampleCoversCheck === false) { + $cfg->error = true; +} + +$cfg->bookCoversCheck = is_writable($cfg->COVERS_PATH . 'book'); +if ($cfg->bookCoversCheck === false) { + $cfg->error = true; +} + +$cfg->consoleCoversCheck = is_writable($cfg->COVERS_PATH . 'console'); +if ($cfg->consoleCoversCheck === false) { + $cfg->error = true; +} + +$cfg->movieCoversCheck = is_writable($cfg->COVERS_PATH . 'movies'); +if ($cfg->movieCoversCheck === false) { + $cfg->error = true; +} + +$cfg->musicCoversCheck = is_writable($cfg->COVERS_PATH . 'music'); +if ($cfg->musicCoversCheck === false) { + $cfg->error = true; +} + +$cfg->previewCoversCheck = is_writable($cfg->COVERS_PATH . 'preview'); +if ($cfg->previewCoversCheck === false) { + $cfg->error = true; +} + +$cfg->sampleCoversCheck = is_writable($cfg->COVERS_PATH . 'sample'); +if ($cfg->sampleCoversCheck === false) { + $cfg->error = true; +} + +$cfg->videoCoversCheck = is_writable($cfg->COVERS_PATH . 'video'); +if ($cfg->videoCoversCheck === false) { + $cfg->error = true; +} + +$cfg->configCheck = is_writable(NN_WWW); +if ($cfg->configCheck === false) { + $cfg->configCheck = is_file(NN_WWW); + if ($cfg->configCheck === true) { + $cfg->configCheck = false; + $cfg->error = true; + } else { + $cfg->configCheck = is_writable(NN_WWW); + if ($cfg->configCheck === false) { + $cfg->error = true; + } + } +} + +$cfg->lockCheck = is_writable($cfg->INSTALL_DIR . 'install.lock'); +if ($cfg->lockCheck === false) { + $cfg->lockCheck = is_file($cfg->INSTALL_DIR . 'install.lock'); + if ($cfg->lockCheck === true) { + $cfg->lockCheck = false; + $cfg->error = true; + } else { + $cfg->lockCheck = is_writable($cfg->INSTALL_DIR); + if ($cfg->lockCheck === false) { + $cfg->error = true; + } + } +} + +$cfg->pearCheck = @include 'System.php'; +$cfg->pearCheck = class_exists('System'); +if (!$cfg->pearCheck) { + $cfg->error = true; +} + +$cfg->schemaCheck = false; +if (is_readable($cfg->DB_DIR . 'mysql-ddl.sql')) { + $cfg->schemaCheck = true; +} +if ($cfg->schemaCheck === false) { + $cfg->error = true; +} + +// Don't set error = true for these as we only want to display a warning. +$cfg->phpCheck = (version_compare(PHP_VERSION, NN_MINIMUM_PHP_VERSION, '>=')) ? true : false; +$cfg->timelimitCheck = (ini_get('max_execution_time') >= 120) ? true : false; +$cfg->memlimitCheck = (ini_get('memory_limit') >= 1024 || ini_get('memory_limit') == -1) ? true : false; +$cfg->opensslCheck = extension_loaded("openssl"); +$cfg->exifCheck = extension_loaded("exif"); +$cfg->timezoneCheck = (ini_get('date.timezone') != ""); + +if (preg_match('/apache/i', $_SERVER['SERVER_SOFTWARE'])) { + $cfg->rewriteCheck = (function_exists("apache_get_modules") && in_array("mod_rewrite", apache_get_modules())) ? true : false; +} else { + $cfg->rewriteCheck = true; +} + +// Load previous config.php. +if (file_exists(NN_WWW . 'config.php') && is_readable(NN_WWW . 'config.php')) { + $tmpCfg = file_get_contents(NN_WWW . 'config.php'); + $cfg->setConfig($tmpCfg); +} + +if (!$cfg->error) { + $cfg->setSession(); +} + +$page->smarty->assign('cfg', $cfg); + +$page->smarty->assign('page', $page); + +$page->content = $page->smarty->fetch('step1.tpl'); +$page->render(); \ No newline at end of file diff --git a/lib/copy_this/www/install/step2.php b/lib/copy_this/www/install/step2.php new file mode 100644 index 000000000..5dda6a849 --- /dev/null +++ b/lib/copy_this/www/install/step2.php @@ -0,0 +1,225 @@ +title = "Database Setup"; + +$cfg = new Install(); + +if (!$cfg->isInitialized()) { + header("Location: index.php"); + die(); +} + +/** + * Check if the database exists. + * + * @param string $dbName The name of the database to be checked. + * @param string $dbType mysql + * @param PDO $pdo Class PDO instance. + * + * @return bool + */ +function databaseCheck($dbName, $dbType, $pdo) +{ + // Return value. + $retVal = false; + + // Prepare queries. + $stmt = ($dbType === "mysql" ? 'SHOW DATABASES' : 'SELECT datname AS Database FROM pg_database'); + $stmt = $pdo->prepare($stmt); + $stmt->setFetchMode(PDO::FETCH_ASSOC); + + // Run the query. + $stmt->execute(); + $tables = $stmt->fetchAll(); + + // Store the query result as an array. + $tablearr = array(); + foreach ($tables as $table) { + $tablearr[] = $table; + } + + // Loop over the query result. + foreach ($tablearr as $tab) { + + // Check if the database is found. + if (isset($tab["Database"])) { + if ($tab["Database"] == $dbName) { + $retVal = true; + break; + } + } + + if (isset($tab["database"])) { + if ($tab["database"] == $dbName) { + $retVal = true; + break; + } + } + } + return $retVal; +} + +$cfg = $cfg->getSession(); + +if ($page->isPostBack()) { + $cfg->doCheck = true; + + // Get the information the user typed into the website. + $cfg->DB_HOST = trim($_POST['host']); + $cfg->DB_PORT = trim($_POST['sql_port']); + $cfg->DB_SOCKET = trim($_POST['sql_socket']); + $cfg->DB_USER = trim($_POST['user']); + $cfg->DB_PASSWORD = trim($_POST['pass']); + $cfg->DB_NAME = trim($_POST['db']); + $cfg->DB_SYSTEM = strtolower(trim($_POST['db_system'])); + $cfg->error = false; + + // Check if user selected right DB type. + if (!in_array($cfg->DB_SYSTEM, array('mysql'))) { + $cfg->emessage = 'Invalid database system. Must be: mysql ; Not: ' . $cfg->DB_SYSTEM; + $cfg->error = true; + } else { + // Connect to the SQL server. + try { + $pdo = new DB( + array( + 'checkVersion' => true, + 'createDb' => true, + 'dbhost' => $cfg->DB_HOST, + 'dbname' => $cfg->DB_NAME, + 'dbpass' => $cfg->DB_PASSWORD, + 'dbport' => $cfg->DB_PORT, + 'dbsock' => $cfg->DB_SOCKET, + 'dbtype' => $cfg->DB_SYSTEM, + 'dbuser' => $cfg->DB_USER, + ) + ); + $cfg->dbConnCheck = true; + } catch (\PDOException $e) { + $cfg->emessage = 'Unable to connect to the SQL server.'; + $cfg->error = true; + $cfg->dbConnCheck = false; + } catch (\RuntimeException $e) { + switch ($e->getCode()) { + case 1: + case 2: + case 3: + $cfg->error = true; + $cfg->emessage = $e->getMessage(); + break; + default: + var_dump($e); + throw new \RuntimeException($e->getMessage(), $e->getCode(), $e); + } + } + + // Check if the MySQL version is correct. + $goodVersion = false; + if (!$cfg->error) { + try { + $goodVersion = $pdo->isDbVersionAtLeast(NN_MINIMUM_MYSQL_VERSION); + } catch (\PDOException $e) { + $goodVersion = false; + $cfg->error = true; + $cfg->emessage = 'Could not get version from SQL server.'; + } + + if ($goodVersion === false) { + $cfg->error = true; + $cfg->emessage = + 'You are using an unsupported version of ' . + $cfg->DB_SYSTEM . + ' the minimum allowed version is ' . + NN_MINIMUM_MYSQL_VERSION; + } + } + } + + // Start inserting data into the DB. + if (!$cfg->error) { + $cfg->setSession(); + + $DbSetup = new \newznab\db\DbUpdate( + array( + 'backup' => false, + 'db' => $pdo, + ) + ); + + try { + $DbSetup->processSQLFile(); // Setup default schema + $DbSetup->loadTables(); // Load default data files + $DbSetup->processSQLFile( // Process any custom stuff. + array( + 'filepath' => NN_RES . 'db' . DS . 'schema' . DS . 'mysql-data.sql' + ) + ); + } catch (\PDOException $err) { + $cfg->error = true; + $cfg->emessage = "Error inserting: (" . $err->getMessage() . ")"; + } + + if (!$cfg->error) { + // Check one of the standard tables was created and has data. + $dbInstallWorked = false; + $reschk = $pdo->query("SELECT COUNT(*) AS num FROM countries"); + if ($reschk === false) { + $cfg->dbCreateCheck = false; + $cfg->error = true; + $cfg->emessage = 'Could not select data from your database.'; + } else { + foreach ($reschk as $row) { + if ($row['num'] > 0) { + $dbInstallWorked = true; + break; + } + } + } + + $ver = new \newznab\utility\Versions(); + $patch = $ver->getSQLPatchFromFiles(); + $pdo->setSetting(['..sqlpatch' => $patch]); + + if ($dbInstallWorked) { + $ver = new \newznab\utility\Versions(); + $patch = $ver->getSQLPatchFromFiles(); + if ($patch > 0) { + $updateSettings = $pdo->setSetting( + [ + 'section' => '', + 'subsection' => '', + 'name' => 'sqlpatch', + 'value' => $patch + ]); + } else { + $updateSettings = false; + } + + // If it all worked, move to the next page. + if ($updateSettings) { + header("Location: ?success"); + if (file_exists($cfg->DB_DIR . '/post_install.php')) { + exec("php " . $cfg->DB_DIR . "/post_install.php ${pdo}"); + } + exit(); + } else { + $cfg->error = true; + $cfg->emessage = "Could not update sqlpatch to '$patch' for your database."; + } + } else { + $cfg->dbCreateCheck = false; + $cfg->error = true; + $cfg->emessage = 'Could not select data from your database.'; + } + } + } +} + +$page->smarty->assign('cfg', $cfg); +$page->smarty->assign('page', $page); +$page->content = $page->smarty->fetch('step2.tpl'); +$page->render(); diff --git a/lib/copy_this/www/install/step3.php b/lib/copy_this/www/install/step3.php new file mode 100644 index 000000000..6bff097d7 --- /dev/null +++ b/lib/copy_this/www/install/step3.php @@ -0,0 +1,78 @@ +title = "OpenSSL Setup"; + +$cfg = new Install(); + +if (!$cfg->isInitialized()) { + header("Location: index.php"); + die(); +} + +$cfg = $cfg->getSession(); + +if ($page->isPostBack()) { + $cfg->doCheck = true; + + $cfg->nZEDb_SSL_CAFILE = trim($_POST['cafile']); + $cfg->nZEDb_SSL_CAPATH = trim($_POST['capath']); + $cfg->nZEDb_SSL_VERIFY_PEER = (isset($_POST['verifypeer']) ? (trim($_POST['verifypeer']) == '1' ? true : false) : false); + $cfg->nZEDb_SSL_VERIFY_HOST = (isset($_POST['verifyhost']) ? (trim($_POST['verifyhost']) == '1' ? true : false) : false); + $cfg->nZEDb_SSL_ALLOW_SELF_SIGNED = (isset($_POST['allowselfsigned']) ? (trim($_POST['allowselfsigned']) == '1' ? true : false) : false); + + // If the user doesn't want to verify peer, disable everything. + if (!$cfg->nZEDb_SSL_VERIFY_PEER) { + $cfg->nZEDb_SSL_ALLOW_SELF_SIGNED = true; + $cfg->nZEDb_SSL_VERIFY_HOST = false; + $cfg->nZEDb_SSL_CAFILE = $cfg->nZEDb_SSL_CAPATH = ''; + } + + // If both paths are empty, disable everything. + if (!$cfg->nZEDb_SSL_CAPATH && !$cfg->nZEDb_SSL_CAFILE) { + $cfg->nZEDb_SSL_VERIFY_PEER = $cfg->nZEDb_SSL_VERIFY_HOST = false; + $cfg->nZEDb_SSL_ALLOW_SELF_SIGNED = true; + $cfg->nZEDb_SSL_CAFILE = $cfg->nZEDb_SSL_CAPATH = ''; + } + + // Make sure the files and all paths are readable. + if ($cfg->nZEDb_SSL_CAFILE != '') { + if (!checkPathsReadable($cfg->nZEDb_SSL_CAFILE)) { + $cfg->error = 'Invalid ca file path or it is not readable or the folders up to it are not readable.'; + } else if (1) { + + } + } + if ($cfg->nZEDb_SSL_CAPATH != '' && !checkPathsReadable($cfg->nZEDb_SSL_CAPATH)) { + $cfg->error = 'Invalid ca folder path or it is not readable or the folders up to it are not readable.'; + } + + if (!$cfg->error) { + $cfg->setSession(); + header("Location: ?success"); + die(); + } +} + +$page->smarty->assign('cfg', $cfg); +$page->smarty->assign('page', $page); + +$page->content = $page->smarty->fetch('step3.tpl'); +$page->render(); + +function checkPathsReadable($location) +{ + $paths = preg_split('#\/#', $location); + $directory = ''; + if ($paths && count($paths)) { + foreach ($paths as $path) { + $directory .= DS . $path; + if (!is_readable($directory)) { + return false; + } + } + return true; + } + return false; +} diff --git a/lib/copy_this/www/install/step4.php b/lib/copy_this/www/install/step4.php new file mode 100644 index 000000000..77f967fc4 --- /dev/null +++ b/lib/copy_this/www/install/step4.php @@ -0,0 +1,60 @@ +title = "News Server Setup"; + +$cfg = new Install(); + +if (!$cfg->isInitialized()) { + header("Location: index.php"); + die(); +} + +$cfg = $cfg->getSession(); + +if ($page->isPostBack()) { + $cfg->doCheck = true; + + $cfg->NNTP_SERVER = trim($_POST['server']); + $cfg->NNTP_USERNAME = trim($_POST['user']); + $cfg->NNTP_PASSWORD = trim($_POST['pass']); + $cfg->NNTP_PORT = (trim($_POST['port']) == '') ? 119 : trim($_POST['port']); + $cfg->NNTP_SSLENABLED = (isset($_POST['ssl']) ? (trim($_POST['ssl']) == '1' ? true : false) : false); + $cfg->NNTP_SOCKET_TIMEOUT = (is_numeric(trim($_POST['socket_timeout'])) ? (int)trim($_POST['socket_timeout']) : 120); + + require_once NN_LIBS . 'Net_NNTP/NNTP/Client.php'; + $test = new Net_NNTP_Client(); + $pear_obj = new PEAR(); + + $enc = false; + if ($cfg->NNTP_SSLENABLED) { + $enc = "tls"; + } + + // test connection + $cfg->nntpCheck = $test->connect($cfg->NNTP_SERVER, $enc, $cfg->NNTP_PORT); + if ($pear_obj->isError($cfg->nntpCheck)) { + $cfg->nntpCheck->message = 'Connection error, check your server name, port and SSL: (' . $cfg->nntpCheck->getMessage() . ')'; + $cfg->error = true; + } else if ($cfg->NNTP_USERNAME != '' && $cfg->NNTP_PASSWORD != '') { + //test authentication if username and password are provided + $cfg->nntpCheck = $test->authenticate($cfg->NNTP_USERNAME, $cfg->NNTP_PASSWORD); + if ($pear_obj->isError($cfg->nntpCheck)) { + $cfg->nntpCheck->message = 'Authentication error, check your username and password: (' . $cfg->nntpCheck->getMessage() . ')'; + $cfg->error = true; + } + } + + if (!$cfg->error) { + $cfg->setSession(); + header("Location: ?success"); + die(); + } +} + +$page->smarty->assign('cfg', $cfg); +$page->smarty->assign('page', $page); + +$page->content = $page->smarty->fetch('step4.tpl'); +$page->render(); \ No newline at end of file diff --git a/lib/copy_this/www/install/step5.php b/lib/copy_this/www/install/step5.php new file mode 100644 index 000000000..cecc2c4ea --- /dev/null +++ b/lib/copy_this/www/install/step5.php @@ -0,0 +1,34 @@ +title = "Save Settings"; + +$cfg = new Install(); + +if (!$cfg->isInitialized()) { + header("Location: index.php"); + die(); +} + +$cfg = $cfg->getSession(); + +$cfg->saveConfigCheck = $cfg->saveConfig(); +if ($cfg->saveConfigCheck === false) { + $cfg->error = true; +} + +$cfg->saveLockCheck = $cfg->saveInstallLock(); +if ($cfg->saveLockCheck === false) { + $cfg->error = true; +} + +if (!$cfg->error) { + $cfg->setSession(); +} + +$page->smarty->assign('cfg', $cfg); +$page->smarty->assign('page', $page); + +$page->content = $page->smarty->fetch('step5.tpl'); +$page->render(); \ No newline at end of file diff --git a/lib/copy_this/www/install/step6.php b/lib/copy_this/www/install/step6.php new file mode 100644 index 000000000..1e4a953e7 --- /dev/null +++ b/lib/copy_this/www/install/step6.php @@ -0,0 +1,66 @@ +title = "Setup Admin User"; + +$cfg = new Install(); + +if (!$cfg->isInitialized()) { + header("Location: index.php"); + die(); +} + +$cfg = $cfg->getSession(); + +if ($page->isPostBack()) { + $cfg->doCheck = true; + + $cfg->ADMIN_USER = trim($_POST['user']); + $cfg->ADMIN_FNAME = trim($_POST['fname']); + $cfg->ADMIN_LNAME = trim($_POST['lname']); + $cfg->ADMIN_PASS = trim($_POST['pass']); + $cfg->ADMIN_EMAIL = trim($_POST['email']); + + if ($cfg->ADMIN_USER == '' || $cfg->ADMIN_PASS == '' || $cfg->ADMIN_EMAIL == '') { + $cfg->error = true; + } else { + require_once NN_LIB . 'controllers/Users.php'; + $user = new Users(); + if (!$user->isValidUsername($cfg->ADMIN_USER)) { + $cfg->error = true; + $cfg->ADMIN_USER = ''; + } else { + $usrCheck = $user->getByUsername($cfg->ADMIN_USER); + if ($usrCheck) { + $cfg->error = true; + $cfg->ADMIN_USER = ''; + } + } + if (!$user->isValidEmail($cfg->ADMIN_EMAIL)) { + $cfg->error = true; + $cfg->ADMIN_EMAIL = ''; + } + + if (!$cfg->error) { + $cfg->adminCheck = $user->add($cfg->ADMIN_USER, $cfg->ADMIN_FNAME, $cfg->ADMIN_LNAME, $cfg->ADMIN_PASS, $cfg->ADMIN_EMAIL, 2, ''); + if (!is_numeric($cfg->adminCheck)) { + $cfg->error = true; + } else { + $user->login($cfg->adminCheck, "", 1); + } + } + } + + if (!$cfg->error) { + $cfg->setSession(); + header("Location: ?success"); + die(); + } +} + +$page->smarty->assign('cfg', $cfg); +$page->smarty->assign('page', $page); + +$page->content = $page->smarty->fetch('step6.tpl'); +$page->render(); diff --git a/lib/copy_this/www/install/step7.php b/lib/copy_this/www/install/step7.php new file mode 100644 index 000000000..d4d736451 --- /dev/null +++ b/lib/copy_this/www/install/step7.php @@ -0,0 +1,111 @@ +title = "File Paths"; +} + +$cfg = new Install(); + +if (!$cfg->isInitialized()) { + header("Location: index.php"); + die(); +} + +$cfg = $cfg->getSession(); + +if ($page->isPostBack()) { + $cfg->doCheck = true; + + $cfg->NZB_PATH = trim($_POST['nzbpath']); + $cfg->COVERS_PATH = trim($_POST['coverspath']); + $cfg->UNRAR_PATH = trim($_POST['tmpunrarpath']); + + if (extension_loaded('posix') && strtolower(substr(PHP_OS, 0, 3)) !== 'win') { + $group = posix_getgrgid(posix_getgid()); + $fixString = '

Another solution is to run:
chown -R YourUnixUserName:' . $group['name'] . ' ' . NN_ROOT . + '
Then give your user access to the group:
usermod -a -G ' . $group['name'] . ' YourUnixUserName' . + '
Finally give read/write access to your user/group:
chmod -R 774 ' . NN_ROOT; + $page->smarty->assign('fixString', $fixString); + } + + if ($cfg->NZB_PATH == '') { + $cfg->error = true; + } else { + $cfg->nzbPathCheck = is_writable($cfg->NZB_PATH); + if ($cfg->nzbPathCheck === false) { + $cfg->error = true; + } + + $lastchar = substr($cfg->NZB_PATH, strlen($cfg->NZB_PATH) - 1); + if ($lastchar != "/") { + $cfg->NZB_PATH = $cfg->NZB_PATH . "/"; + } + } + + if ($cfg->UNRAR_PATH == '') { + $cfg->error = true; + } else { + $cfg->unrarPathCheck = is_writable($cfg->NZB_PATH); + if ($cfg->unrarPathCheck === false) { + $cfg->error = true; + } + + $lastchar = substr($cfg->UNRAR_PATH, strlen($cfg->UNRAR_PATH) - 1); + if ($lastchar != "/") { + $cfg->UNRAR_PATH = $cfg->UNRAR_PATH . "/"; + } + } + /* + if ($cfg->COVERS_PATH == '') { + $cfg->error = true; + } else { + \nzedb\utility\Utility::trailingSlash($cfg->COVERS_PATH); + + $cfg->coverPathCheck = is_writable($cfg->COVERS_PATH); + if ($cfg->coverPathCheck === false) { + $cfg->error = true; + } + } + */ + + if (!$cfg->error) { + if (!file_exists($cfg->UNRAR_PATH)) { + mkdir($cfg->UNRAR_PATH); + } + + $pdo = new DB(); + $sql1 = sprintf("UPDATE site SET value = %s WHERE setting = 'nzbpath'", $pdo->escapeString($cfg->NZB_PATH)); + $sql2 = sprintf("UPDATE site SET value = %s WHERE setting = 'tmpunrarpath'", $pdo->escapeString($cfg->UNRAR_PATH)); + $sql3 = sprintf("UPDATE site SET value = %s WHERE setting = 'coverspath'", $pdo->escapeString($cfg->COVERS_PATH)); + if ($pdo->queryExec($sql1) === false || $pdo->queryExec($sql2) === false || $pdo->queryExec($sql3) === false) { + $cfg->error = true; + } + + if ($cfg->error !== true) { + if ($cfg->COVERS_PATH != NN_WWW . 'covers' . DS) { + // TODO clean up old covers location if 'empty' (i.e. only contains the versioned files). + } + + if ($cfg->NZB_PATH != NN_ROOT . 'nzbfiles' . DS) { + // TODO clean up old nzbfiles location if 'empty' (i.e. only contains the versioned files). + } + } + } + + if (!$cfg->error) { + $cfg->setSession(); + header("Location: ?success"); + die(); + } +} + +$page->smarty->assign('cfg', $cfg); +$page->smarty->assign('page', $page); + +$page->content = $page->smarty->fetch('step7.tpl'); +$page->render(); diff --git a/lib/copy_this/www/install/views/installpage.tpl b/lib/copy_this/www/install/views/installpage.tpl new file mode 100644 index 000000000..1af39589f --- /dev/null +++ b/lib/copy_this/www/install/views/installpage.tpl @@ -0,0 +1,21 @@ + + + + + {$page->title} + + + {$page->head} + + +

Newznab

+
+

{$page->title}

+ {$page->content} + + +
+ + diff --git a/lib/copy_this/www/install/views/step1.tpl b/lib/copy_this/www/install/views/step1.tpl new file mode 100644 index 000000000..a0b400b3d --- /dev/null +++ b/lib/copy_this/www/install/views/step1.tpl @@ -0,0 +1,254 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {if $smarty.server.SERVER_SOFTWARE|truncate:8:"" == 'lighttpd'} + + + {else} + + + {/if} + + + + + + +
checkstatus
Checking for Curl support:{if !$cfg->curlCheck}
The PHP installation lacks support for curl.{/if}
{if $cfg->curlCheck}OK{else}Warning{/if}
Checking for sha1():{if !$cfg->sha1Check}
The PHP installation lacks support for sha1.{/if}
{if $cfg->sha1Check}OK{else}Error{/if}
Checking for crypt():{if !$cfg->cryptCheck}
The PHP installation lacks support for crypt.{/if}
{if $cfg->sha1Check}OK{else}Error{/if}
Checking PHP's version:{if !$cfg->phpCheck}
Your PHP version is lower than recommended ({$cfg->minPhpVersion}). You may encounter errors if you proceed.{/if}
{if $cfg->phpCheck}OK{else}Warning{/if}
Checking for Pear:{if !$cfg->pearCheck}
Cannot find PEAR. To install PEAR follow the instructions at http://pear.php.net/manual/en/installation.php{/if}
{if $cfg->pearCheck}OK{else}Error{/if}
Checking PHP PDO extension:{if !$cfg->PDOCheck}
The PHP installation lacks support for PDO.{/if}
{if $cfg->PDOCheck}OK{else}Error{/if}
Checking PHP GD extension:{if !$cfg->gdCheck}
The PHP installation lacks support for GD.{/if}
{if $cfg->gdCheck}OK{else}Warning{/if}
Checking PHP OpenSSL Extension:{if !$cfg->opensslCheck}
Your PHP installation does not have the openssl extension loaded. SSL Usenet connections will fail.{/if}
{if $cfg->opensslCheck}OK{else}Warning{/if}
Checking PHP EXIF Extension:{if !$cfg->exifCheck}
Your PHP installation does not have the exif extension loaded. It is required for NFO checking and various other functions.{/if}
{if $cfg->exifCheck}OK{else}Warning{/if}
Checking PHP json extension:{if !$cfg->jsonCheck}
The PHP installation lacks support for json.{/if}
{if $cfg->jsonCheck}OK{else}Error{/if}
Checking PHP date.timezone:{if !$cfg->timezoneCheck}
You have no default timezone set in php.ini. e.g date.timezone = America/New_York{/if}
{if $cfg->timezoneCheck}OK{else}Warning{/if}
Checking PHP max_execution_time:{if !$cfg->timelimitCheck}
Your PHP installation's max_execution_time setting is low, please consider increasing it >= 120{/if}
{if $cfg->timelimitCheck}OK{else}Warning{/if}
Checking PHP memory_limit:{if !$cfg->memlimitCheck}
Your PHP installation's memory_limit setting is low, please consider increasing it >= 1024M.{/if}
{if $cfg->memlimitCheck}OK{else}Warning{/if}
Checking if the Smarty compile dir is writable: + {if !$cfg->cacheCheck}
+ + The template compile dir must be writable.

+ A quick solution is to run:
+ chmod 777 {$cfg->SMARTY_DIR}/templates_c + {$fixString} +
+ {/if} +
{if $cfg->cacheCheck}OK{else}Error{/if}
Checking if the anime covers dir is writable: + {if !$cfg->animeCoversCheck}
+ + The covers/anime dir must be writable.
+ A quick solution is to run:
+ chmod 777 {$cfg->COVERS_PATH}anime + {$fixString} +
+ {/if} +
{if $cfg->animeCoversCheck}OK{else}Error{/if}
Checking if the audio covers dir is writable: + {if !$cfg->audioCoversCheck}
+ + The covers/audio dir must be writable.
+ A quick solution is to run:
+ chmod 777 {$cfg->COVERS_PATH}audio + {$fixString} +
+ {/if} +
{if $cfg->audioCoversCheck}OK{else}Error{/if}
Checking if the audio sample dir is writable: + {if !$cfg->audiosampleCoversCheck}
+ + The covers/audiosample dir must be writable.
+ A quick solution is to run:
+ chmod 777 {$cfg->COVERS_PATH}audiosample + {$fixString} +
+ {/if} +
{if $cfg->audiosampleCoversCheck}OK{else}Error{/if}
Checking if the book covers dir is writable: + {if !$cfg->bookCoversCheck}
+ + The covers/book dir must be writable.
+ A quick solution is to run:
+ chmod 777 {$cfg->COVERS_PATH}book + {$fixString} +
+ {/if} +
{if $cfg->bookCoversCheck}OK{else}Error{/if}
Checking if the console covers dir is writable: + {if !$cfg->consoleCoversCheck}
+ + The covers/console dir must be writable.
+ A quick solution is to run:
+ chmod 777 {$cfg->COVERS_PATH}console + {$fixString} +
+ {/if} +
{if $cfg->consoleCoversCheck}OK{else}Error{/if}
Checking if the movie covers dir is writable: + {if !$cfg->movieCoversCheck}
+ + The covers/movies dir must be writable.
+ A quick solution is to run:
+ chmod 777 {$cfg->COVERS_PATH}movies + {$fixString} +
+ {/if} +
{if $cfg->movieCoversCheck}OK{else}Error{/if}
Checking if the music covers dir is writable: + {if !$cfg->musicCoversCheck}
+ + The covers/music dir must be writable.
+ A quick solution is to run:
+ chmod 777 {$cfg->COVERS_PATH}music + {$fixString} +
+ {/if} +
{if $cfg->musicCoversCheck}OK{else}Error{/if}
Checking if the preview picture dir is writable: + {if !$cfg->previewCoversCheck}
+ + The covers/preview dir must be writable.
+ A quick solution is to run:
+ chmod 777 {$cfg->COVERS_PATH}preview + {$fixString} +
+ {/if} +
{if $cfg->previewCoversCheck}OK{else}Error{/if}
Checking if the sample picture dir is writable: + {if !$cfg->sampleCoversCheck}
+ + The covers/sample dir must be writable.
+ A quick solution is to run:
+ chmod 777 {$cfg->COVERS_PATH}sample + {$fixString} +
+ {/if} +
{if $cfg->sampleCoversCheck}OK{else}Error{/if}
Checking if the video sample dir is writable: + {if !$cfg->videoCoversCheck}
+ + The covers/video dir must be writable.
+ A quick solution is to run:
+ chmod 777 {$cfg->COVERS_PATH}video + {$fixString} +
+ {/if} +
{if $cfg->videoCoversCheck}OK{else}Error{/if}
Checking if the config.php file is writable: + {if !$cfg->configCheck}
+ + The installer cannot write to {$cfg->WWW_TOP}.
+ A quick solution is to run:
+ chmod 777 {$cfg->WWW_TOP} + {$fixString} +
+ {/if} +
{if $cfg->configCheck}OK{else}Error{/if}
Checking if the install.lock file is writable: + {if !$cfg->lockCheck}
+ + The installer cannot write to {$cfg->INSTALL_DIR}/install.lock.
+ A quick solution is to run:
+ chmod 777 {$cfg->INSTALL_DIR} + {$fixString} +
+ {/if} +
{if $cfg->lockCheck}OK{else}Error{/if}
Checking for schema files:{if !$cfg->schemaCheck}
One or all of the schema files are missing, please make sure they are placed placed in: {$cfg->DB_DIR}/{/if}
{if $cfg->schemaCheck}OK{else}Error{/if}
Instructions for Lighttpd's mod_rewrite:
It is not possible for me to check you have enabled this properly! YOU will need to ensure that "mod_rewrite" is included in server.modules, check lighttpd for this, also ensure the rewrite rules are installed for your host. See misc/urlrewriting/lighttpd.txt for examples.
WarningChecking for Apache's mod_rewrite:{if !$cfg->rewriteCheck}
The Apache module mod_rewrite is not loaded. This module is required, please enable it if you are running Apache{/if}
{if $cfg->rewriteCheck}OK{else}Warning{/if}
Checking PHP sessions path permissions:{if !$cfg->sessionsPathPermissions}
The PHP sessions path ({$sessionsSavePath}) does not have read or write access.{/if}
{if $cfg->sessionsPathPermissions}OK{else}Error{/if}
+ +
+ {if !$cfg->error} +

No problems were found and you are ready to install.

+
+ {else} +
Errors encountered - newznab-tmux will not function correctly unless these problems are solved.
+ {/if} +
\ No newline at end of file diff --git a/lib/copy_this/www/install/views/step2.tpl b/lib/copy_this/www/install/views/step2.tpl new file mode 100644 index 000000000..dc17a00b8 --- /dev/null +++ b/lib/copy_this/www/install/views/step2.tpl @@ -0,0 +1,78 @@ +{if $page->isSuccess()} +
+

The database setup is correct, you may continue to the next step.

+
+
+ +
+
+
+{else} + +

This page will attempt to use your database information provided below to connect to the database and create the required tables and initial data.

+ + +
+
+ {if $cfg->error} +
+ The following error(s) were encountered:
+ {if $cfg->dbConnCheck === false} + • Unable to connect to database:
{$cfg->emessage}

+ {elseif $cfg->dbNameCheck === false} + • Unable to select database:
{$cfg->emessage}

+ {elseif $cfg->dbCreateCheck === false} + • Unable to create database and data. Check permissions of your mysql user.
+ {else} + {$cfg->emessage}
+ {/if} +
+
+ {/if} +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+ +{/if} \ No newline at end of file diff --git a/lib/copy_this/www/install/views/step3.tpl b/lib/copy_this/www/install/views/step3.tpl new file mode 100644 index 000000000..2a37238bc --- /dev/null +++ b/lib/copy_this/www/install/views/step3.tpl @@ -0,0 +1,82 @@ +{if $page->isSuccess()} +
+

The openssl setup looks correct, you may continue to the next step.

+
+
+ +
+
+
+{else} +
+

An openssl CA bundle file is recommended to verify the authenticity of remote certificates when connecting to various servers using TLS/SSL.

+
    +
  • If you do not have a CA bundle, you can download one here.
  • +
  • You can place the CA bundle in the /etc/ssl/certs/ folder if you are on linux.
  • +
  • The file must be readable by both your web user and your CLI user running scripts.
  • +
+ + + + + + + + + + + + + + + + + + + + + + +
+ +
+ Location of Certificate Authority file on local filesystem which will be used if the Verify Peer option is enabled to authenticate the identity of the remote peer. +
Example: /etc/ssl/certs/cacert.pem +
+
+ +
+ If the ca bundle cert file is not specified or if the certificate is not found there, you can specify a directory here which will be searched for a suitable certificate. +
Example: /etc/ssl/certs/
+
+ nZEDb_SSL_VERIFY_PEER=="true"}checked="checked"{/if} /> +
+ Enabling this requires the ca bundle cert file path to be set.
+ Disabling this will disable TLS/SSL remote certificate verification which is not recommended. +
+
+ nZEDb_SSL_VERIFY_HOST=="true"}checked="checked"{/if} /> +
+ This makes sure the host is who they say they are.
+ See this link for detailed info.
+ You might need to disable this as some providers are using the wrong CN in their certs (probably because they are cheap and re-using a cert and rely on people disabling host verification or lack knowledge).
+ Note that disabling this is a security risk and you should consider getting a usenet provider that has a proper certificate. +
+
+ nZEDb_SSL_ALLOW_SELF_SIGNED=="true"}checked="checked"{/if} /> +
+ Enabling this will not verify self-signed openssl certificates.
+ Note that you will require non self-signed certificates for sabnzbd/nzbget/etc if you disable this. +
+
+
+ {if $cfg->error} +
+ The following error was encountered:
+ • {$cfg->error}


+
+ {/if} + +
+
+{/if} \ No newline at end of file diff --git a/lib/copy_this/www/install/views/step4.tpl b/lib/copy_this/www/install/views/step4.tpl new file mode 100644 index 000000000..e5e6ffd3e --- /dev/null +++ b/lib/copy_this/www/install/views/step4.tpl @@ -0,0 +1,98 @@ +{if $page->isSuccess()} +
+

The news server setup is correct, you may continue to the next step.

+
+
+{else} +
+

If you have a primary news server (NNTP), please provide the following information (make sure the information is correct, some servers do not check if the password is good):

+ + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
e.g. eu.news.astraweb.com
+
+ +
+ +
e.g. 119 or 443,563 for SSL
+
+ NNTP_SSLENABLED=="true"}checked="checked"{/if} /> +
+ +
Seconds to time out when we lost connection to usenet. Default is 120 seconds.
+
+

(optional) If you have an alternate news server (NNTP), please provide the following information (make sure the information is correct, some servers do not check if the password is good):

+ + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
e.g. eu.news.astraweb.com
+
+ +
+ +
e.g. 119 or 443,563 for SSL
+
+ NNTP_SSLENABLED_A=="true"}checked="checked"{/if} /> +
+ +
Seconds to time out when we lost connection to usenet. Default is 120 seconds.
+
+
+ {if $cfg->error} +
+ The following error was encountered:
+ • {$cfg->error}


+
+ {/if} + +
+
+{/if} \ No newline at end of file diff --git a/lib/copy_this/www/install/views/step5.tpl b/lib/copy_this/www/install/views/step5.tpl new file mode 100644 index 000000000..66974d6eb --- /dev/null +++ b/lib/copy_this/www/install/views/step5.tpl @@ -0,0 +1,17 @@ +
+ {if !$cfg->error} +

The configuration file has been saved, you may continue to the next step.

+
+ {else} + {if !$cfg->saveConfigCheck} +

Error saving {$cfg->NN_WWW}/config.php.

+

Please save the config.php yourself by creating:
{$cfg->NN_WWW}/config.php
and setting its contents to the following:

+

+ {/if} + {if !$cfg->saveLockCheck} +
+

Error saving {$cfg->INSTALL_DIR}/install.lock

+

Please save the install.lock yourself by creating:
{$cfg->INSTALL_DIR}/install.lock

+ {/if} + {/if} +
diff --git a/lib/copy_this/www/install/views/step6.tpl b/lib/copy_this/www/install/views/step6.tpl new file mode 100644 index 000000000..5e2d2ffc2 --- /dev/null +++ b/lib/copy_this/www/install/views/step6.tpl @@ -0,0 +1,44 @@ +{if $page->isSuccess()} +
+

The admin user has been setup, you may continue to the next step.

+
+
+{else} + +

This will set up an administrator account you can use to change site settings.

+ +
+ + + + + + + + + + + + + +
+ +
+ {if $cfg->error} +
+ The following error(s) were encountered:
+ {if $cfg->ADMIN_USER == ''}• Invalid username
{/if} + {if $cfg->ADMIN_PASS == ''}• Invalid password
{/if} + {if $cfg->ADMIN_EMAIL == ''}• Invalid email
{/if} +
+
+ {/if} + +
+
+ +{/if} \ No newline at end of file diff --git a/lib/copy_this/www/install/views/step7.tpl b/lib/copy_this/www/install/views/step7.tpl new file mode 100644 index 000000000..47355b667 --- /dev/null +++ b/lib/copy_this/www/install/views/step7.tpl @@ -0,0 +1,58 @@ +{if $page->isSuccess()} +
+

Install Complete!

+
+

Continue to the admin home page to give your site a name and learn how to start indexing usenet.

+
+{else} + +

You must accept or change these file paths. This is the location where your covers, NZB, and temporary files are stored:

+
+ + + + + + + + + + + + + +
+ +
+ {if $cfg->error} +
+ The following error was encountered:
+
+ {if !$cfg->nzbPathCheck} + + The installer cannot write to {$cfg->NZB_PATH}.
+ A quick solution is to run:
+ chmod -R 777 {$cfg->NZB_PATH} + {$fixString} {$cfg->NZB_PATH} +

+
+ {/if} + {if !$cfg->coverPathCheck}
The installer cannot write to {$cfg->COVERS_PATH}. A quick solution is to run:
chmod -R 777 {$cfg->COVERS_PATH}

{/if} + {if !$cfg->unrarPathCheck} + + The installer cannot write to {$cfg->UNRAR_PATH}.
+ A quick solution is to run:
+ chmod -R 777 {$cfg->UNRAR_PATH} + {$fixString} {$cfg->UNRAR_PATH} +

+
+ {/if} +
+
+ {/if} + +
+ +
+ +{/if} \ No newline at end of file diff --git a/lib/copy_this/www/lib/nzbget.php b/lib/copy_this/www/lib/nzbget.php deleted file mode 100644 index 31f8adfed..000000000 --- a/lib/copy_this/www/lib/nzbget.php +++ /dev/null @@ -1,245 +0,0 @@ -serverurl = $page->serverurl; - $this->uid = $page->userdata['id']; - $this->rsstoken = $page->userdata['rsstoken']; - - switch($page->site->sabintegrationtype) - { - case SABnzbd::INTEGRATION_TYPE_USER: - if (!empty($_COOKIE['nzbget_'.$this->uid.'__host'])) - { - $this->url = $_COOKIE['nzbget_'.$this->uid.'__host']; - $this->username = $_COOKIE['nzbget_'.$this->uid.'__username']; - $this->password = $_COOKIE['nzbget_'.$this->uid.'__password']; - } - elseif (!empty($page->userdata['nzbgeturl'])) - { - $this->url = $page->userdata['nzbgeturl']; - $this->username = $page->userdata['nzbgetusername']; - $this->password = $page->userdata['nzbgetpassword']; - } - $this->integrated = SABnzbd::INTEGRATION_TYPE_USER; - break; - case SABnzbd::INTEGRATION_TYPE_SITEWIDE: - if (!empty($page->site->nzbgeturl)) - { - $this->url = $page->site->nzbgeturl; - $this->username = $page->site->nzbgetusername; - $this->password = $page->site->nzbgetpassword; - } - $this->integrated = SABnzbd::INTEGRATION_TYPE_SITEWIDE; - break; - } - } - - public function fullurl() - { - $url = $this->url; - if (preg_match('/(?Phttps?):\/\/(?P.+?)(:(?P\d+\/)|\/)$/i', - $url, - $matches)) { - return - $matches['protocol'] . - '://' . - $this->username . - ':' . - $this->password . - '@' . - $matches['url'] . - (isset($matches['port']) ? ':' . $matches['port'] : (substr($matches['url'], -1) === '/' ? '' : '/')) . - 'xmlrpc/'; - } else { - return false; - } - } - - public function sendToNZBGet($guid) - { - $releases = new Releases(); - $reldata = $releases->getByGuid($guid); - $url = "{$this->serverurl}getnzb/{$guid}&i={$this->uid}&r={$this->rsstoken}"; - $header = << - - appendurl - - - {$reldata['searchname']}.nzb - - - {$reldata['category_name']} - - - 0 - - - >False - - - - $url - - - - -NZBGet_URL; - - Utility::getUrl(['url' => $this->fullurl()."appendurl",'method' => "POST", 'postdata' => $header, 'verifycert' => false]); - } - - public function pauseAll() - { - $header = << - - pausedownload2 - - - 1 - - - -NZBGet_PAUSE_ALL; - - Utility::getUrl(['url' => $this->fullurl().'pausedownload2', 'method' => "POST", 'postdata' =>$header, 'verifycert' => false]); - } - - public function resumeAll() - { - $header = << - - resumedownload2 - - - 1 - - -' -NZBGet_RESUME_ALL; - - Utility::getUrl(['url' => $this->fullurl().'resumedownload2', 'method' => "POST", 'postdata' => $header, 'verifycert' => false]); - } - - public function delFromQueue($id) - { - $header = << - - editqueue - - - GroupDelete - - - 0 - - - "" - - - - - $id - - - - - -NZBGet_DELETE_FROM_QUEUE; - - Utility::getUrl(['url' => $this->fullurl().'editqueue', 'method' => "POST", 'postdata' => $header, 'verifycert' => false]); - } - - public function getQueue() - { - $data = Utility::getUrl(['url' => $this->fullurl().'listgroups', 'verifycert' => false]); - $retVal = false; - if ($data) { - $xml = simplexml_load_string($data); - if ($xml) { - $retVal = array(); - $i = 0; - foreach ($xml->params->param->value->array->data->value as $value) { - foreach ($value->struct->member as $member) { - $value = (array)$member->value; - $value = array_shift($value); - if (!is_object($value)) { - $retVal[$i][(string)$member->name] = $value; - } - } - $i++; - } - } - } - - return $retVal; - } - - public function status() - { - $data = Utility::getUrl(['url' => $this->fullurl()."status", 'verifycert' => false]); - $retVal = false; - if ($data) { - $xml = simplexml_load_string($data); - if ($xml) { - foreach ($xml->params->param->value->struct->member as $member) { - $value = (array)$member->value; - $value = array_shift($value); - if (!is_object($value)) { - $retVal[(string)$member->name] = $value; - } - } - } - } - - return $retVal; - } - - public function checkCookie() - { - $res = false; - if (isset($_COOKIE['nzbget_'.$this->uid.'__host'])) - $res = true; - if (isset($_COOKIE['nzbget_'.$this->uid.'__username'])) - $res = true; - if (isset($_COOKIE['nzbget_'.$this->uid.'__password'])) - $res = true; - - return $res; - } - - public function setCookie($host, $username, $password) - { - setcookie('nzbget_'.$this->uid.'__host', $host, (time()+2592000)); - setcookie('nzbget_'.$this->uid.'__username', $username, (time()+2592000)); - setcookie('nzbget_'.$this->uid.'__password', $password, (time()+2592000)); - } - - public function unsetCookie() - { - setcookie('nzbget_'.$this->uid.'__host', '', (time()-2592000)); - setcookie('nzbget_'.$this->uid.'__username', '', (time()-2592000)); - setcookie('nzbget_'.$this->uid.'__password', '', (time()-2592000)); - } -} \ No newline at end of file diff --git a/lib/copy_this/www/pages/.htaccess b/lib/copy_this/www/pages/.htaccess new file mode 100644 index 000000000..3418e55a6 --- /dev/null +++ b/lib/copy_this/www/pages/.htaccess @@ -0,0 +1 @@ +deny from all \ No newline at end of file diff --git a/lib/copy_this/www/pages/ajax_mediainfo.php b/lib/copy_this/www/pages/ajax_mediainfo.php index 2fb05a2d8..a0d9a77be 100644 --- a/lib/copy_this/www/pages/ajax_mediainfo.php +++ b/lib/copy_this/www/pages/ajax_mediainfo.php @@ -1,5 +1,4 @@ isLoggedIn()) { $page->show403(); } diff --git a/lib/copy_this/www/pages/ajax_mymovies.php b/lib/copy_this/www/pages/ajax_mymovies.php new file mode 100644 index 000000000..a65370bd0 --- /dev/null +++ b/lib/copy_this/www/pages/ajax_mymovies.php @@ -0,0 +1,90 @@ +isLoggedIn()) + $page->show403(); + +$um = new UserMovies(); + + +if (isset($_REQUEST["del"])) +{ + $usermovies = $um->delMovie($users->currentUserId(), $_REQUEST["del"]); +} +elseif (isset($_REQUEST["add"])) +{ + // + // derive cats from user preferences + // + $cats = array(); + $cats[] = "2030"; + $cats[] = "2040"; + + $m = new Movie(false); + $mi = $m->getMovieInfo($_REQUEST["add"]); + if (!$mi) + $m->updateMovieInfo($_REQUEST["add"]); + + $usermovies = $um->addMovie($users->currentUserId(), $_REQUEST["add"], $cats); +} +else +{ + if (!isset($_REQUEST["id"])) + $page->show404(); + + $m = new Movie(false); + + if (is_numeric($_REQUEST["id"])) + { + $prop = $m->fetchTmdbProperties($_REQUEST["id"]); + if ($prop !== false) + $res = array($prop); + } + else + { + $res = $m->searchTmdb($_REQUEST["id"]); + } + + $imdbids = array(); + if ($res) + { + foreach ($res as $movie) + { + if (isset($movie['title']) && isset($movie['imdb_id'])) + { + $imdbids[] = str_replace("tt", "", $movie['imdb_id']); + } + else + { + // no results + } + } + + if (count($imdbids) == 0) + { + print "

No results found

"; + } + else + { + $ourmovieimdbs = array(); + if (count($imdbids) > 0) + { + $m = new Movie(); + $allmovies = $m->getMovieInfoMultiImdb($imdbids); + foreach ($allmovies as $ourmovie) + if ($ourmovie["relimdb"] != "") + $ourmovieimdbs[$ourmovie["imdbID"]] = $ourmovie["imdbID"]; + } + + $userimdbs = array(); + $usermovies = $um->getMovies($users->currentUserId()); + foreach ($usermovies as $umovie) + $userimdbs[$umovie["imdbID"]] = $umovie["imdbID"]; + + $page->smarty->assign('data', $res); + $page->smarty->assign('ourmovies', $ourmovieimdbs); + $page->smarty->assign('userimdbs', $userimdbs); + + print $page->smarty->fetch('mymovielist.tpl'); + } + } +} \ No newline at end of file diff --git a/lib/copy_this/www/pages/ajax_prehashinfo.php b/lib/copy_this/www/pages/ajax_prehashinfo.php index 8e243054e..78f37a6cf 100644 --- a/lib/copy_this/www/pages/ajax_prehashinfo.php +++ b/lib/copy_this/www/pages/ajax_prehashinfo.php @@ -1,6 +1,4 @@ isLoggedIn()) { $page->show403(); } diff --git a/lib/copy_this/www/pages/ajax_preinfo.php b/lib/copy_this/www/pages/ajax_preinfo.php index d2076ee9d..ac79f6503 100644 --- a/lib/copy_this/www/pages/ajax_preinfo.php +++ b/lib/copy_this/www/pages/ajax_preinfo.php @@ -1,5 +1,4 @@ isLoggedIn() || $page->userdata["canpre"] != 1) $page->show403(); diff --git a/lib/copy_this/www/pages/ajax_profile.php b/lib/copy_this/www/pages/ajax_profile.php new file mode 100644 index 000000000..66fb82b81 --- /dev/null +++ b/lib/copy_this/www/pages/ajax_profile.php @@ -0,0 +1,18 @@ +isLoggedIn()) + $page->show403(); + +if (isset($_GET['action']) && $_GET['action'] == "1" && isset($_GET['emailto'])) +{ + $emailto = $_GET['emailto']; + $ret = $users->sendInvite($page->site->title, $page->site->email, $page->serverurl, $users->currentUserId(), $emailto); + if (!$ret) + print "Invite not sent."; + else + print "Invite sent. Alternatively paste them following link to register - ".$ret; +} +else +{ + print "Invite not sent."; +} diff --git a/lib/copy_this/www/pages/ajax_rarfilelist.php b/lib/copy_this/www/pages/ajax_rarfilelist.php new file mode 100644 index 000000000..74f0b9ec4 --- /dev/null +++ b/lib/copy_this/www/pages/ajax_rarfilelist.php @@ -0,0 +1,21 @@ +isLoggedIn()) + $page->show403(); + +if (!isset($_REQUEST["id"])) + $page->show404(); + +$rf = new ReleaseFiles(); +$files = $rf->getByGuid($_REQUEST["id"]); + +if (count($files) == 0) + print "No files"; +else +{ + //print "

rar archive contains...

\n"; + print "
    \n"; + foreach ($files as $f) + print "
  • ".htmlentities($f["name"], ENT_QUOTES)." ".($f["passworded"] == 1?"":"")."
  • \n"; + print "
"; +} \ No newline at end of file diff --git a/lib/copy_this/www/pages/ajax_release-admin.php b/lib/copy_this/www/pages/ajax_release-admin.php new file mode 100644 index 000000000..26d0bb60f --- /dev/null +++ b/lib/copy_this/www/pages/ajax_release-admin.php @@ -0,0 +1,44 @@ +smarty->assign('action', $action); +$page->smarty->assign('idArr', $id); + +switch($action) +{ + case 'doedit': + case 'edit': + $success = false; + if ($action == 'doedit') + { + $upd = $releases->updatemulti($_REQUEST["id"], $_REQUEST["category"], $_REQUEST["grabs"], $_REQUEST["rageID"], $_REQUEST["season"], $_REQUEST['imdbID']); + if ($upd !== false) { + $success = true; + } else { + + } + } + $page->smarty->assign('success', $success); + $page->smarty->assign('from',(isset($_REQUEST['from'])?$_REQUEST['from']:'')); + $page->smarty->assign('catlist',$category->getForSelect()); + $page->content = $page->smarty->fetch('ajax_release-edit.tpl'); + echo $page->content; + + break; + case 'dodelete': + $releases->delete($_REQUEST["id"], true); + break; + case 'dorebuild': + $releases->rebuildmulti($_REQUEST["id"]); + break; + default: + $page->show404(); + break; +} diff --git a/lib/copy_this/www/pages/ajax_resetusergrabs-admin.php b/lib/copy_this/www/pages/ajax_resetusergrabs-admin.php new file mode 100644 index 000000000..8d91e95d4 --- /dev/null +++ b/lib/copy_this/www/pages/ajax_resetusergrabs-admin.php @@ -0,0 +1,21 @@ +delDownloadRequests($id); + break; + case 'api': + $u->delApiRequests($id); + break; + default: + $page->show404(); + break; +} + diff --git a/lib/copy_this/www/pages/ajax_tvinfo.php b/lib/copy_this/www/pages/ajax_tvinfo.php index 99ced1e6b..2ee77e9e2 100644 --- a/lib/copy_this/www/pages/ajax_tvinfo.php +++ b/lib/copy_this/www/pages/ajax_tvinfo.php @@ -1,6 +1,4 @@ isLoggedIn()) $page->show403(); diff --git a/lib/copy_this/www/pages/anime.php b/lib/copy_this/www/pages/anime.php index 0b75f5280..d6562ddff 100644 --- a/lib/copy_this/www/pages/anime.php +++ b/lib/copy_this/www/pages/anime.php @@ -1,6 +1,4 @@ isLoggedIn()) $page->show403(); diff --git a/lib/copy_this/www/pages/api.php b/lib/copy_this/www/pages/api.php index 5f2161fde..cb12d5f4e 100644 --- a/lib/copy_this/www/pages/api.php +++ b/lib/copy_this/www/pages/api.php @@ -1,8 +1,5 @@ $page->settings]); +$releases = new \Releases(['Settings' => $page->settings]); if (isset($_GET['extended']) && $_GET['extended'] == 1) { $page->smarty->assign('extended', '1'); @@ -199,7 +196,7 @@ switch ($function) { if (!$nfo) showApiError(300); - $nforaw = cp437toUTF($nfo["nfo"]); + $nforaw = Utility::cp437toUTF($nfo["nfo"]); $page->smarty->assign('release',$reldata); $page->smarty->assign('nfo',$nfo); $page->smarty->assign('nfoutf',$nforaw); @@ -659,10 +656,10 @@ function addCoverURL(&$releases, callable $getCoverURL) /** * Add language from media info XML to release search names. * @param array $releases - * @param \DB $settings + * @param \newznab\db\DB $settings * @return array */ -function addLanguage(&$releases, DB $settings) +function addLanguage(&$releases, \newznab\db\DB $settings) { if ($releases && count($releases)) { foreach ($releases as $key => $release) { diff --git a/lib/copy_this/www/pages/apihelp.php b/lib/copy_this/www/pages/apihelp.php new file mode 100644 index 000000000..07de39259 --- /dev/null +++ b/lib/copy_this/www/pages/apihelp.php @@ -0,0 +1,10 @@ +title = "Api"; +$page->meta_title = "Api Help Topics"; +$page->meta_keywords = "view,nzb,api,details,help,json,rss,atom"; +$page->meta_description = "View description of the site Nzb Api."; + +$page->content = $page->smarty->fetch('apidesc.tpl'); +$page->render(); + diff --git a/lib/copy_this/www/pages/bookmodal.php b/lib/copy_this/www/pages/bookmodal.php new file mode 100644 index 000000000..3b8577d7e --- /dev/null +++ b/lib/copy_this/www/pages/bookmodal.php @@ -0,0 +1,36 @@ +isLoggedIn()) + $page->show403(); + +if (isset($_GET["id"]) && ctype_digit($_GET["id"])) +{ + $book = $b->getBookInfo($_GET['id']); + if (!$book) + $page->show404(); + + $page->smarty->assign('book', $book); + + $page->title = "Info for ".$book['title']; + $page->meta_title = ""; + $page->meta_keywords = ""; + $page->meta_description = ""; + $page->smarty->registerPlugin('modifier', 'ss', 'stripslashes'); + + $modal = false; + if (isset($_GET['modal'])) + { + $modal = true; + $page->smarty->assign('modal', true); + } + + $page->content = $page->smarty->fetch('viewbook.tpl'); + + if ($modal) + echo $page->content; + else + $page->render(); +} + diff --git a/lib/copy_this/www/pages/books.php b/lib/copy_this/www/pages/books.php index c29ccbcfc..57a181636 100644 --- a/lib/copy_this/www/pages/books.php +++ b/lib/copy_this/www/pages/books.php @@ -1,6 +1,4 @@ $page->settings]); diff --git a/lib/copy_this/www/pages/browsegroup.php b/lib/copy_this/www/pages/browsegroup.php index e66e44af1..069bab64e 100644 --- a/lib/copy_this/www/pages/browsegroup.php +++ b/lib/copy_this/www/pages/browsegroup.php @@ -1,5 +1,4 @@ isLoggedIn()) { $page->show403(); } diff --git a/lib/copy_this/www/pages/calendar.php b/lib/copy_this/www/pages/calendar.php index a8d74cc53..88bc548b5 100644 --- a/lib/copy_this/www/pages/calendar.php +++ b/lib/copy_this/www/pages/calendar.php @@ -1,5 +1,4 @@ isLoggedIn()) { $page->show403(); diff --git a/lib/copy_this/www/pages/cart.php b/lib/copy_this/www/pages/cart.php new file mode 100644 index 000000000..3bc7d9ed2 --- /dev/null +++ b/lib/copy_this/www/pages/cart.php @@ -0,0 +1,50 @@ +isLoggedIn()) + $page->show403(); + +if (isset($_REQUEST["add"])) +{ + if (isset($_GET['add']) && !empty($_GET['add'])) + $ids = array($_GET['add']); + elseif (isset($_POST['add']) && is_array($_POST['add'])) + $ids = $_POST['add']; + + $releases = new Releases; + $data = $releases->getByGuid($ids); + + if (!$data) + $page->show404(); + + foreach($data as $d) + $users->addCart($users->currentUserId(), $d["ID"]); +} +elseif (isset($_REQUEST["delete"])) +{ + if (isset($_GET['delete']) && !empty($_GET['delete'])) + $ids = array($_GET['delete']); + elseif (isset($_POST['delete']) && is_array($_POST['delete'])) + $ids = $_POST['delete']; + + if (isset($ids)) + $users->delCartByGuid($ids, $users->currentUserId()); + + if (!isset($_POST['delete'])) + header("Location: ".WWW_TOP."/cart"); + + die(); +} +else +{ + $page->meta_title = "My Nzb Cart"; + $page->meta_keywords = "search,add,to,cart,nzb,description,details"; + $page->meta_description = "Manage Your Nzb Cart"; + + $results = $users->getCart($users->currentUserId()); + $page->smarty->assign('results', $results); + + $page->content = $page->smarty->fetch('cart.tpl'); + $page->render(); +} + + diff --git a/lib/copy_this/www/pages/console.php b/lib/copy_this/www/pages/console.php index 743e43293..655228bd4 100644 --- a/lib/copy_this/www/pages/console.php +++ b/lib/copy_this/www/pages/console.php @@ -1,7 +1,4 @@ isLoggedIn()) + $page->show403(); + +if (isset($_GET["id"]) && ctype_digit($_GET["id"])) +{ + $con = $console->getConsoleInfo($_GET['id']); + if (!$con) + $page->show404(); + + $page->smarty->assign('console', $con); + + $page->title = "Info for ".$con['title']; + $page->meta_title = ""; + $page->meta_keywords = ""; + $page->meta_description = ""; + $page->smarty->registerPlugin('modifier', 'ss', 'stripslashes'); + + $modal = false; + if (isset($_GET['modal'])) + { + $modal = true; + $page->smarty->assign('modal', true); + } + + $page->content = $page->smarty->fetch('viewconsole.tpl'); + + if ($modal) + echo $page->content; + else + $page->render(); +} + diff --git a/lib/copy_this/www/pages/contact-us.php b/lib/copy_this/www/pages/contact-us.php index d989d60cd..349341e9a 100644 --- a/lib/copy_this/www/pages/contact-us.php +++ b/lib/copy_this/www/pages/contact-us.php @@ -1,5 +1,6 @@ userdata != null) + $role = $page->userdata["role"]; + +$contentid = 0; +if (isset($_GET["id"])) + $contentid = $_GET["id"]; + +if ($contentid == 0) + $content = $contents->getIndex(); +else + $content = $contents->getByID($contentid, $role); + +if ($content == null) + $page->show404(); + +$page->smarty->assign('content',$content); +$page->meta_title = $content["title"]; +$page->meta_keywords = $content["metakeywords"]; +$page->meta_description = $content["metadescription"]; + +$page->content = $page->smarty->fetch('content.tpl'); +$page->render(); + diff --git a/lib/copy_this/www/pages/details.php b/lib/copy_this/www/pages/details.php index de7fbd90e..c3a05e76f 100644 --- a/lib/copy_this/www/pages/details.php +++ b/lib/copy_this/www/pages/details.php @@ -1,20 +1,4 @@ isLoggedIn()) $page->show403(); @@ -99,7 +83,7 @@ if (isset($_GET["id"])) 'https://www.youtube.com/v/' . $youtubeM[1] . '" type="application/x-shockwave-flash">'; } else { - $mov['trailer'] = imdb_trailers($data['imdbid']); + $mov['trailer'] = \newznab\utility\Utility::imdb_trailers($data['imdbid']); } if ($mov && isset($mov['title'])) { @@ -141,21 +125,18 @@ if (isset($_GET["id"])) $mus = ''; if ($data['musicinfoid'] != '') { - require_once(WWW_DIR."/lib/music.php"); $music = new Musik(['Settings' => $page->settings]); $mus = $music->getMusicInfo($data['musicinfoid']); } $book = ''; if ($data['bookinfoid'] != '') { - require_once(WWW_DIR."/lib/book.php"); $b = new Book(); $book = $b->getBookInfo($data['bookinfoid']); } $con = ''; if ($data['consoleinfoid'] != '') { - require_once(WWW_DIR."/lib/console.php"); $c = new Console(); $con = $c->getConsoleInfo($data['consoleinfoid']); } diff --git a/lib/copy_this/www/pages/dlbrowse.php b/lib/copy_this/www/pages/dlbrowse.php new file mode 100644 index 000000000..043f23099 --- /dev/null +++ b/lib/copy_this/www/pages/dlbrowse.php @@ -0,0 +1,116 @@ +isLoggedIn()) + $page->show403(); + +$r = new Releases(); +$s = new Sites(); +$site = $s->get(); + +$db = new DB(); + +if ($site->sabvdir == "" || $site->sabcompletedir == "" || !file_exists($site->sabcompletedir)) + $page->show404(); + +if (!Utility::endsWith($site->sabcompletedir, "/")) + $site->sabcompletedir.="/"; +if (!Utility::endsWith($site->sabvdir, "/")) + $site->sabvdir.="/"; + + +$basepath = $site->sabcompletedir; +$webpath = $site->sabvdir; + +$subpath = ""; +if (isset($_REQUEST["sp"])) + $subpath = urldecode($_REQUEST["sp"]); + +$listmode = true; +if (isset($_REQUEST["lm"])) + $listmode = ($_REQUEST["lm"] == "1"); + +$path = $basepath.$subpath; +$webpath.=$subpath; + +if (!Utility::startsWith(realpath($path), realpath($basepath))) + $page->show403(); + +$files = glob(preg_replace('/(\*|\?|\[)/', '[$1]', $path)."/*"); + +$items = array(); +$dirs = array(); +foreach($files as $f) +{ + $i = array(); + $i["name"] = basename($f); + $i["isdir"] = (is_dir($f)?1:0); + $i["fullname"] = $f; + $i["webpath"] = $webpath."/".$i["name"].($i["isdir"] == 1?"/":""); + $i["mtime"] = filemtime($f); + $i["pathinfo"] = pathinfo($f); + if ($i["isdir"] == 1) + { + $i["pathinfo"]["extension"] = ""; + $dirs[] = $i["name"]; + } + else + { + $i["size"] = filesize($f); + } + $items[$i["name"]] = $i; +} + +if (!$listmode) +{ + $relres = $r->getByNames($dirs); + while ($rel = $db->getAssocArray($relres)) + { + if (isset($items[$rel["searchname"]])) + $items[$rel["searchname"]]["release"] = $rel; + } +} + +uasort($items, 'sortbymodified'); + +$page->smarty->assign('results', $items); +$page->smarty->assign('lm', $listmode); + +if ($subpath != "") + $page->smarty->assign('subpath', $subpath."/"); + +$parentpath =""; +if ($subpath != "") +{ + $pos = strrpos($subpath, "/"); + if ($pos !== false) + $parentpath = substr($subpath, 0, $pos); + else + $parentpath = "-1"; + + $page->smarty->assign('parentpath', $parentpath); +} + +$page->meta_title = "download browse"; +$page->meta_keywords = "downloads,browse"; +$page->meta_description = "browse downloaded files"; + +$page->content = $page->smarty->fetch('dlbrowse.tpl'); +$page->render(); + + +function sortbymodified($a, $b) +{ + if ($a["isdir"] == 1 && $b["isdir"] == 0) + return -1; + if ($a["isdir"] == 0 && $b["isdir"] == 1) + return 1; + + if ($a["mtime"] == $b["mtime"]) { + return 0; + } + return ($a["mtime"] > $b["mtime"]) ? -1 : 1; +} \ No newline at end of file diff --git a/lib/copy_this/www/pages/failed.php b/lib/copy_this/www/pages/failed.php index 44e47c059..ecb3385f3 100644 --- a/lib/copy_this/www/pages/failed.php +++ b/lib/copy_this/www/pages/failed.php @@ -1,7 +1,4 @@ $page->settings]); $users = new Users(); diff --git a/lib/copy_this/www/pages/filelist.php b/lib/copy_this/www/pages/filelist.php index 2d66a90ac..059624109 100644 --- a/lib/copy_this/www/pages/filelist.php +++ b/lib/copy_this/www/pages/filelist.php @@ -1,6 +1,4 @@ isLoggedIn()) $page->show404(); diff --git a/lib/copy_this/www/pages/forum.php b/lib/copy_this/www/pages/forum.php new file mode 100644 index 000000000..035464b0b --- /dev/null +++ b/lib/copy_this/www/pages/forum.php @@ -0,0 +1,42 @@ +isLoggedIn()) + $page->show403(); + +if ($page->isPostBack()) +{ + if (!isset($_POST["addSubject"]) || empty($_POST["addSubject"])) + $page->show403(); + if (!isset($_POST["addMessage"]) || empty($_POST["addMessage"])) + $page->show403(); + + $forum->add(0, $users->currentUserId(), $_POST["addSubject"], $_POST["addMessage"]); + header("Location:".WWW_TOP."/forum"); + die(); +} +$browsecount = $forum->getBrowseCount(); + +$offset = (isset($_REQUEST["offset"]) && ctype_digit($_REQUEST['offset'])) ? $_REQUEST["offset"] : 0; + +$results = array(); +$results = $forum->getBrowseRange($offset, ITEMS_PER_PAGE); + +$page->smarty->assign('pagertotalitems',$browsecount); +$page->smarty->assign('pageroffset',$offset); +$page->smarty->assign('pageritemsperpage',ITEMS_PER_PAGE); +$page->smarty->assign('pagerquerybase', WWW_TOP."/forum?offset="); +$page->smarty->assign('pagerquerysuffix', "#results"); + +$pager = $page->smarty->fetch("pager.tpl"); +$page->smarty->assign('pager', $pager); +$page->smarty->assign('results',$results); + +$page->meta_title = "Forum"; +$page->meta_keywords = "forum,chat,posts"; +$page->meta_description = "Forum"; + +$page->content = $page->smarty->fetch('forum.tpl'); +$page->render(); + diff --git a/lib/copy_this/www/pages/forumpost.php b/lib/copy_this/www/pages/forumpost.php new file mode 100644 index 000000000..1030da5d4 --- /dev/null +++ b/lib/copy_this/www/pages/forumpost.php @@ -0,0 +1,32 @@ +isLoggedIn()) + $page->show403(); + +$id = $_GET["id"] + 0; + +$forum = new Forum(); +if ($page->isPostBack()) +{ + $forum->add($id, $users->currentUserId(), "", $_POST["addReply"]); + header("Location:".WWW_TOP."/forumpost/".$id."#last"); + die(); +} + +$results = $forum->getPosts($id); +if (count($results) == 0) +{ + header("Location:".WWW_TOP."/forum"); + die(); +} + +$page->meta_title = "Forum Post"; +$page->meta_keywords = "view,forum,post,thread"; +$page->meta_description = "View forum post"; + +$page->smarty->assign('results', $results); + +$page->content = $page->smarty->fetch('forumpost.tpl'); +$page->render(); + + diff --git a/lib/copy_this/www/pages/games.php b/lib/copy_this/www/pages/games.php index 8a416ade2..3a2801b1b 100644 --- a/lib/copy_this/www/pages/games.php +++ b/lib/copy_this/www/pages/games.php @@ -1,7 +1,5 @@ isLoggedIn()) { $page->show403(); } diff --git a/lib/copy_this/www/pages/getimage.php b/lib/copy_this/www/pages/getimage.php new file mode 100644 index 000000000..b4c0663e7 --- /dev/null +++ b/lib/copy_this/www/pages/getimage.php @@ -0,0 +1,30 @@ +isLoggedIn()) + $page->show403(); + +if (!isset($_GET["type"]) || !isset($_GET["id"]) || !ctype_digit($_GET["id"])) + $page->show404(); + +// +// user requested a tvrage image. +// +if ($_GET["type"] == "tvrage") +{ + $rage = new TvRage; + $r = $rage->getByID($_GET["id"]); + if (!$r) + $page->show404(); + + header("Content-type: image/jpeg"); + print $r["imgdata"]; + die(); +} +else +{ + $page->show404(); +} + diff --git a/lib/copy_this/www/pages/getnzb.php b/lib/copy_this/www/pages/getnzb.php index 70dfc6cd4..56e832e44 100644 --- a/lib/copy_this/www/pages/getnzb.php +++ b/lib/copy_this/www/pages/getnzb.php @@ -1,6 +1,4 @@ settings); $rel = new Releases(['Settings' => $page->settings]); diff --git a/lib/copy_this/www/pages/logout.php b/lib/copy_this/www/pages/logout.php new file mode 100644 index 000000000..7ca3f4fb6 --- /dev/null +++ b/lib/copy_this/www/pages/logout.php @@ -0,0 +1,4 @@ +logout(); + +header("Location: ".WWW_TOP."/"); diff --git a/lib/copy_this/www/pages/movie.php b/lib/copy_this/www/pages/movie.php new file mode 100644 index 000000000..ff9ea7eea --- /dev/null +++ b/lib/copy_this/www/pages/movie.php @@ -0,0 +1,41 @@ +isLoggedIn()) + $page->show403(); + +if (isset($_GET["id"]) && ctype_digit($_GET["id"])) +{ + $mov = $movie->getMovieInfo($_GET['id']); + + if (!$mov) + $page->show404(); + + $mov['actors'] = $movie->makeFieldLinks($mov, 'actors'); + $mov['genre'] = $movie->makeFieldLinks($mov, 'genre'); + $mov['director'] = $movie->makeFieldLinks($mov, 'director'); + + $page->smarty->assign('movie', $mov); + + $page->title = "Info for ".$mov['title']; + $page->meta_title = ""; + $page->meta_keywords = ""; + $page->meta_description = ""; + $page->smarty->registerPlugin('modifier', 'ss', 'stripslashes'); + + $modal = false; + if (isset($_GET['modal'])) + { + $modal = true; + $page->smarty->assign('modal', true); + } + + $page->content = $page->smarty->fetch('viewmovie.tpl'); + + if ($modal) + echo $page->content; + else + $page->render(); +} + diff --git a/lib/copy_this/www/pages/movies.php b/lib/copy_this/www/pages/movies.php index 58ca99c3b..c8ae6594a 100644 --- a/lib/copy_this/www/pages/movies.php +++ b/lib/copy_this/www/pages/movies.php @@ -1,6 +1,4 @@ $page->settings]); diff --git a/lib/copy_this/www/pages/movietrailer.php b/lib/copy_this/www/pages/movietrailer.php new file mode 100644 index 000000000..9c9fd29e1 --- /dev/null +++ b/lib/copy_this/www/pages/movietrailer.php @@ -0,0 +1,37 @@ +isLoggedIn()) + $page->show403(); + +if (isset($_GET["id"]) && ctype_digit($_GET["id"])) +{ + $mov = $movie->getMovieInfo($_GET['id']); + + if (!$mov) + $page->show404(); + + $page->smarty->assign('movie', $mov); + + $page->title = "Info for ".$mov['title']; + $page->meta_title = ""; + $page->meta_keywords = ""; + $page->meta_description = ""; + $page->smarty->registerPlugin('modifier', 'ss', 'stripslashes'); + + $modal = false; + if (isset($_GET['modal'])) + { + $modal = true; + $page->smarty->assign('modal', true); + } + + $page->content = $page->smarty->fetch('viewmovietrailer.tpl'); + + if ($modal) + echo $page->content; + else + $page->render(); +} + diff --git a/lib/copy_this/www/pages/music.php b/lib/copy_this/www/pages/music.php index 6b18f5a24..d08b95ddd 100644 --- a/lib/copy_this/www/pages/music.php +++ b/lib/copy_this/www/pages/music.php @@ -1,7 +1,4 @@ isLoggedIn()) { $page->show403(); diff --git a/lib/copy_this/www/pages/musicmodal.php b/lib/copy_this/www/pages/musicmodal.php new file mode 100644 index 000000000..17ec9006f --- /dev/null +++ b/lib/copy_this/www/pages/musicmodal.php @@ -0,0 +1,37 @@ +isLoggedIn()) + $page->show403(); + +if (isset($_GET["id"]) && ctype_digit($_GET["id"])) +{ + $mus = $music->getMusicInfo($_GET['id']); + + if (!$mus) + $page->show404(); + + $page->smarty->assign('music', $mus); + + $page->title = "Info for ".$mus['title']; + $page->meta_title = ""; + $page->meta_keywords = ""; + $page->meta_description = ""; + $page->smarty->registerPlugin('modifier', 'ss', 'stripslashes'); + + $modal = false; + if (isset($_GET['modal'])) + { + $modal = true; + $page->smarty->assign('modal', true); + } + + $page->content = $page->smarty->fetch('viewmusic.tpl'); + + if ($modal) + echo $page->content; + else + $page->render(); +} + diff --git a/lib/copy_this/www/pages/mymovies.php b/lib/copy_this/www/pages/mymovies.php new file mode 100644 index 000000000..07a5315d4 --- /dev/null +++ b/lib/copy_this/www/pages/mymovies.php @@ -0,0 +1,13 @@ +isLoggedIn()) + $page->show403(); + +$page->title = "My Movies"; +$page->meta_title = "My Movies"; +$page->meta_keywords = "couch,potato,movie,add"; +$page->meta_description = "Manage Your Movies"; + +$page->content = $page->smarty->fetch('mymovies.tpl'); +$page->render(); + + diff --git a/lib/copy_this/www/pages/mymoviesedit.php b/lib/copy_this/www/pages/mymoviesedit.php new file mode 100644 index 000000000..33b0ea3ec --- /dev/null +++ b/lib/copy_this/www/pages/mymoviesedit.php @@ -0,0 +1,53 @@ +isLoggedIn()) + $page->show403(); + +$um = new UserMovies(); + +if (isset($_REQUEST["del"])) +{ + $um->delMovie($users->currentUserId(), $_REQUEST["del"]); +} + +$cat = new Category; +$tmpcats = $cat->getChildren(Category::CAT_PARENT_MOVIE, true, $page->userdata["categoryexclusions"]); +$categories = array(); +foreach($tmpcats as $c) + $categories[$c['ID']] = $c['title']; + +$movies = $um->getMovies($users->currentUserId()); +$results = array(); +foreach ($movies as $mov=>$m) +{ + $movcats = explode('|', $m['categoryID']); + if (is_array($movcats) && sizeof($movcats) > 0) + { + $catarr = array(); + foreach ($movcats as $movcat) + { + if (!empty($movcat)) + $catarr[] = $categories[$movcat]; + } + $m['categoryNames'] = implode(', ', $catarr); + } + else + { + $m['categoryNames'] = ''; + + } + $results[$mov] = $m; + +} +$page->smarty->assign('movies', $results); + +$page->title = "Edit My Movies"; +$page->meta_title = "Edit My Movies"; +$page->meta_keywords = "couch,potato,movie,add"; +$page->meta_description = "Manage Your Movies"; + +$page->content = $page->smarty->fetch('mymoviesedit.tpl'); +$page->render(); + + diff --git a/lib/copy_this/www/pages/myshows.php b/lib/copy_this/www/pages/myshows.php new file mode 100644 index 000000000..a68178e87 --- /dev/null +++ b/lib/copy_this/www/pages/myshows.php @@ -0,0 +1,188 @@ +isLoggedIn()) + $page->show403(); + +$us = new UserSeries(); + +$action = isset($_REQUEST['id']) ? $_REQUEST['id'] : ''; +$rid = isset($_REQUEST['subpage']) ? $_REQUEST['subpage'] : ''; + +switch($action) { + case 'delete': + $show = $us->getShow($users->currentUserId(), $rid); + + if (!$show) + $page->show404('Not subscribed'); + else + $us->delShow($users->currentUserId(), $rid); + + if (isset($_REQUEST['from'])) + header("Location:".WWW_TOP.$_REQUEST['from']); + else + header("Location:".WWW_TOP."/myshows"); + break; + case 'add': + case 'doadd': + $show = $us->getShow($users->currentUserId(), $rid); + + if ($show) + { + $page->show404('Already subscribed'); + } + else + { + $db = new DB(); + $show = $db->queryOneRow(sprintf("select releasetitle from tvrage where rageID = %d", $rid)); + if (!$show) + $page->show404('Seriously?'); + } + + if ($action == 'doadd') + { + $category = (isset($_REQUEST['category']) && is_array($_REQUEST['category']) && !empty($_REQUEST['category'])) ? $_REQUEST['category'] : array(); + $us->addShow($users->currentUserId(), $rid, $category); + if (isset($_REQUEST['from'])) + header("Location:".$_REQUEST['from']); + else + header("Location:".WWW_TOP."/myshows"); + } + else + { + $cat = new Category; + $tmpcats = $cat->getChildren(Category::CAT_PARENT_TV, true, $page->userdata["categoryexclusions"]); + $categories = array(); + foreach($tmpcats as $c) + $categories[$c['ID']] = $c['title']; + + $page->smarty->assign('type', 'add'); + $page->smarty->assign('cat_ids', array_keys($categories)); + $page->smarty->assign('cat_names', $categories); + $page->smarty->assign('cat_selected', array()); + $page->smarty->assign('rid', $rid); + $page->smarty->assign('show', $show); + if (isset($_REQUEST['from'])) + $page->smarty->assign('from', $_REQUEST['from']); + $page->content = $page->smarty->fetch('myshows-add.tpl'); + $page->render(); + } + break; + case 'edit': + case 'doedit': + $show = $us->getShow($users->currentUserId(), $rid); + + if (!$show) + $page->show404(); + + if ($action == 'doedit') + { + $category = (isset($_REQUEST['category']) && is_array($_REQUEST['category']) && !empty($_REQUEST['category'])) ? $_REQUEST['category'] : array(); + $us->updateShow($users->currentUserId(), $rid, $category); + if (isset($_REQUEST['from'])) + header("Location:".WWW_TOP.$_REQUEST['from']); + else + header("Location:".WWW_TOP."/myshows"); + } + else + { + $cat = new Category; + + $tmpcats = $cat->getChildren(Category::CAT_PARENT_TV, true, $page->userdata["categoryexclusions"]); + $categories = array(); + foreach($tmpcats as $c) + $categories[$c['ID']] = $c['title']; + + $page->smarty->assign('type', 'edit'); + $page->smarty->assign('cat_ids', array_keys($categories)); + $page->smarty->assign('cat_names', $categories); + $page->smarty->assign('cat_selected', explode('|', $show['categoryID'])); + $page->smarty->assign('rid', $rid); + $page->smarty->assign('show', $show); + if (isset($_REQUEST['from'])) + $page->smarty->assign('from', $_REQUEST['from']); + $page->content = $page->smarty->fetch('myshows-add.tpl'); + $page->render(); + } + break; + case 'browse': + + $page->title = "Browse My Shows"; + $page->meta_title = "My Shows"; + $page->meta_keywords = "search,add,to,cart,nzb,description,details"; + $page->meta_description = "Browse Your Shows"; + + $shows = $us->getShows($users->currentUserId()); + + $releases = new Releases; + $browsecount = $releases->getShowsCount($shows, -1, $page->userdata["categoryexclusions"]); + + $offset = (isset($_REQUEST["offset"]) && ctype_digit($_REQUEST['offset'])) ? $_REQUEST["offset"] : 0; + $ordering = $releases->getBrowseOrdering(); + $orderby = isset($_REQUEST["ob"]) && in_array($_REQUEST['ob'], $ordering) ? $_REQUEST["ob"] : ''; + + $results = array(); + $results = $releases->getShowsRange($shows, $offset, ITEMS_PER_PAGE, $orderby, -1, $page->userdata["categoryexclusions"]); + + $page->smarty->assign('pagertotalitems',$browsecount); + $page->smarty->assign('pageroffset',$offset); + $page->smarty->assign('pageritemsperpage',ITEMS_PER_PAGE); + $page->smarty->assign('pagerquerybase', WWW_TOP."/myshows/browse?ob=".$orderby."&offset="); + $page->smarty->assign('pagerquerysuffix', "#results"); + + $pager = $page->smarty->fetch("pager.tpl"); + $page->smarty->assign('pager', $pager); + + foreach($ordering as $ordertype) + $page->smarty->assign('orderby'.$ordertype, WWW_TOP."/myshows/browse?ob=".$ordertype."&offset=0"); + + $page->smarty->assign('lastvisit',$page->userdata['lastlogin']); + + $page->smarty->assign('results',$results); + + $page->smarty->assign('shows', true); + + $page->content = $page->smarty->fetch('browse.tpl'); + $page->render(); + break; + default: + + $page->title = "My Shows"; + $page->meta_title = "My Shows"; + $page->meta_keywords = "search,add,to,cart,nzb,description,details"; + $page->meta_description = "Manage Your Shows"; + + $cat = new Category; + $tmpcats = $cat->getChildren(Category::CAT_PARENT_TV, true, $page->userdata["categoryexclusions"]); + $categories = array(); + foreach($tmpcats as $c) + $categories[$c['ID']] = $c['title']; + + $shows = $us->getShows($users->currentUserId()); + $results = array(); + foreach ($shows as $showk=>$show) + { + $showcats = explode('|', $show['categoryID']); + if (is_array($showcats) && sizeof($showcats) > 0) + { + $catarr = array(); + foreach ($showcats as $scat) + { + if (!empty($scat)) + $catarr[] = $categories[$scat]; + } + $show['categoryNames'] = implode(', ', $catarr); + } else { + $show['categoryNames'] = ''; + + } + $results[$showk] = $show; + + } + $page->smarty->assign('shows', $results); + + $page->content = $page->smarty->fetch('myshows.tpl'); + $page->render(); + break; +} \ No newline at end of file diff --git a/lib/copy_this/www/pages/newposterwall.php b/lib/copy_this/www/pages/newposterwall.php index d02ed564f..ced2270f4 100644 --- a/lib/copy_this/www/pages/newposterwall.php +++ b/lib/copy_this/www/pages/newposterwall.php @@ -1,7 +1,4 @@ isLoggedIn()) { $page->show403(); diff --git a/lib/copy_this/www/pages/nfo.php b/lib/copy_this/www/pages/nfo.php index 9c72b1eab..79e1b01b3 100644 --- a/lib/copy_this/www/pages/nfo.php +++ b/lib/copy_this/www/pages/nfo.php @@ -1,6 +1,6 @@ show404(); $nfo = $releases->getReleaseNfo($rel['id']); - $nfo['nfoUTF'] = cp437toUTF($nfo['nfo']); + $nfo['nfoUTF'] = Utility::cp437toUTF($nfo['nfo']); $page->smarty->assign('rel', $rel); $page->smarty->assign('nfo', $nfo); diff --git a/lib/copy_this/www/pages/nzbgetqueuedata.php b/lib/copy_this/www/pages/nzbgetqueuedata.php index 283489d8c..5555385c7 100644 --- a/lib/copy_this/www/pages/nzbgetqueuedata.php +++ b/lib/copy_this/www/pages/nzbgetqueuedata.php @@ -1,6 +1,7 @@ isLoggedIn()) { $page->show403(); } diff --git a/lib/copy_this/www/pages/nzbvortex.php b/lib/copy_this/www/pages/nzbvortex.php new file mode 100644 index 000000000..b042dc03f --- /dev/null +++ b/lib/copy_this/www/pages/nzbvortex.php @@ -0,0 +1,90 @@ +isLoggedIn()) + $page->show403(); + +try +{ + if (isset($_GET['isAjax'])) + { + $vortex = new NZBVortex; + + // I guess we Ajax this way. + if (isset($_GET['getOverview'])) + { + $overview = $vortex->getOverview(); + $page->smarty->assign('overview', $overview); + $content = $page->smarty->fetch('nzbvortex-ajax.tpl'); + echo $content; + exit; + } + + if (isset($_GET['addQueue'])) + { + $nzb = $_GET['addQueue']; + $vortex->addQueue($nzb); + exit; + } + + if (isset($_GET['resume'])) + { + $vortex->resume((int)$_GET['resume']); + exit; + } + + if (isset($_GET['pause'])) + { + $vortex->pause((int)$_GET['pause']); + exit; + } + + if (isset($_GET['moveup'])) + { + $vortex->moveUp((int)$_GET['moveup']); + exit; + } + + if (isset($_GET['movedown'])) + { + $vortex->moveDown((int)$_GET['movedown']); + exit; + } + + if (isset($_GET['movetop'])) + { + $vortex->moveTop((int)$_GET['movetop']); + exit; + } + + if (isset($_GET['movebottom'])) + { + $vortex->moveBottom((int)$_GET['movebottom']); + exit; + } + + if (isset($_GET['delete'])) + { + $vortex->delete((int)$_GET['delete']); + exit; + } + + if (isset($_GET['filelist'])) + { + $response = $vortex->getFilelist((int)$_GET['filelist']); + echo json_encode($response); + exit; + } + } +} +catch (Exception $e) +{ + header('HTTP/1.1 500 Internal Server Error'); + printf($e->getMessage()); + exit; +} + +$page->title = 'NZBVortex'; + +$page->content = $page->smarty->fetch('nzbvortex.tpl'); +$page->render(); \ No newline at end of file diff --git a/lib/copy_this/www/pages/opensearch.php b/lib/copy_this/www/pages/opensearch.php new file mode 100644 index 000000000..2fe06c81f --- /dev/null +++ b/lib/copy_this/www/pages/opensearch.php @@ -0,0 +1,4 @@ +smarty->fetch('opensearch.tpl'); + diff --git a/lib/copy_this/www/pages/predb.php b/lib/copy_this/www/pages/predb.php new file mode 100644 index 000000000..893f66b63 --- /dev/null +++ b/lib/copy_this/www/pages/predb.php @@ -0,0 +1,35 @@ +isLoggedIn() || $page->userdata["canpre"] != 1) + $page->show403(); + +$page->title = 'PreDB'; +$page->meta_title = 'View PreDB'; +$page->meta_keywords = 'view,predb,scene,release,information'; +$page->meta_description = 'View PreDB'; + +$query = (isset($_GET['q']) && !empty($_GET['q'])) ? $_GET['q'] : ''; +$category = (isset($_GET['c']) && !empty($_GET['c'])) ? $_GET['c'] : ''; +$preCount = $PreDB->getPreCount($query, $category); + +$offset = (isset($_REQUEST['offset']) && ctype_digit($_REQUEST['offset'])) ? $_REQUEST['offset'] : 0; +$results = $PreDB->getPreRange($offset, ITEMS_PER_PAGE, $query, $category); + +$page->smarty->assign('pagertotalitems', $preCount); +$page->smarty->assign('pageroffset', $offset); +$page->smarty->assign('pageritemsperpage', ITEMS_PER_PAGE); +$page->smarty->assign('pagerquerybase', WWW_TOP."/predb?q=".$query."&c=".$category."&offset="); +$page->smarty->assign('pagerquerysuffix', "#results"); + +$pager = $page->smarty->fetch("pager.tpl"); +$page->smarty->assign('pager', $pager); +$page->smarty->assign('results', $results); +$page->smarty->assign('query', $query); +$page->smarty->assign('category', $category); + +$page->content = $page->smarty->fetch('viewprelist.tpl'); +$page->render(); + + diff --git a/lib/copy_this/www/pages/prehash.php b/lib/copy_this/www/pages/prehash.php index 65490e141..bd58606a0 100644 --- a/lib/copy_this/www/pages/prehash.php +++ b/lib/copy_this/www/pages/prehash.php @@ -1,5 +1,4 @@ isLoggedIn()) { $page->show403(); diff --git a/lib/copy_this/www/pages/prehashinfo.php b/lib/copy_this/www/pages/prehashinfo.php index 13522262b..8971c5943 100644 --- a/lib/copy_this/www/pages/prehashinfo.php +++ b/lib/copy_this/www/pages/prehashinfo.php @@ -1,7 +1,4 @@ query( sprintf(' SELECT p.* @@ -178,7 +175,7 @@ if (isset($_GET['type'])) { case 't': case 'title': if (isset($_GET['title'])) { - $db = new DB(); + $db = new newznab\db\DB(); $preData = $db->query( sprintf('SELECT * FROM prehash p WHERE p.title %s %s %s LIKE %s LIMIT %d OFFSET %d', $newer, @@ -196,7 +193,7 @@ if (isset($_GET['type'])) { case 'm': case 'md5': if (isset($_GET['md5']) && strlen($_GET['title']) === 32) { - $db = new DB(); + $db = new newznab\db\DB(); $preData = $db->query( sprintf('SELECT * FROM prehash p INNER JOIN predbhash ph ON ph.pre_id = p.id WHERE MATCH(hashes) AGAINST (%s) %s %s %s LIMIT %d OFFSET %d', $db->escapeString($_GET['md5']), @@ -213,7 +210,7 @@ if (isset($_GET['type'])) { case 's': case 'sha1': if (isset($_GET['sha1']) && strlen($_GET['sha1']) === 40) { - $db = new DB(); + $db = new newznab\db\DB(); $preData = $db->query( sprintf('SELECT * FROM prehash p INNER JOIN predbhash ph ON ph.pre_id = p.id WHERE MATCH(hashes) AGAINST (%s) %s %s %s LIMIT %d OFFSET %d', $db->escapeString($_GET['sha1']), @@ -229,7 +226,7 @@ if (isset($_GET['type'])) { case 'a': case 'all': - $db = new DB(); + $db = new newznab\db\DB(); $preData = $db->query( sprintf('SELECT * FROM prehash p WHERE 1=1 %s %s %s ORDER BY p.predate DESC LIMIT %d OFFSET %d', $newer, diff --git a/lib/copy_this/www/pages/profile.php b/lib/copy_this/www/pages/profile.php new file mode 100644 index 000000000..186bf04aa --- /dev/null +++ b/lib/copy_this/www/pages/profile.php @@ -0,0 +1,81 @@ +isLoggedIn()) + $page->show403(); + +$userid = 0; +if (isset($_GET["id"])) + $userid = $_GET["id"] + 0; +elseif (isset($_GET["name"])) +{ + $res = $users->getByUsername($_GET["name"]); + if ($res) + $userid = $res["ID"]; +} +else + $userid = $users->currentUserId(); + +$data = $users->getById($userid); +if (!$data) + $page->show404(); + +$invitedby = ''; +if ($data["invitedby"] != "") + $invitedby = $users->getById($data["invitedby"]); + +$page->smarty->assign('apihits', $users->getApiRequests($userid)); +$page->smarty->assign('grabstoday', $users->getDownloadRequests($userid)); +$page->smarty->assign('userinvitedby',$invitedby); +$page->smarty->assign('user',$data); + +$commentcount = $rc->getCommentCountForUser($userid); +$offset = isset($_REQUEST["offset"]) ? $_REQUEST["offset"] : 0; +$page->smarty->assign('pagertotalitems',$commentcount); +$page->smarty->assign('pageroffset',$offset); +$page->smarty->assign('pageritemsperpage',ITEMS_PER_PAGE); +$page->smarty->assign('pagerquerybase', "/profile?id=".$userid."&offset="); +$page->smarty->assign('pagerquerysuffix', "#comments"); + +$pager = $page->smarty->fetch("pager.tpl"); +$page->smarty->assign('pager', $pager); + +$commentslist = $rc->getCommentsForUserRange($userid, $offset, ITEMS_PER_PAGE); +$page->smarty->assign('commentslist',$commentslist); + +$downloadlist = $users->getDownloadRequestsForUserAndAllHostHashes($userid); +$page->smarty->assign('downloadlist',$downloadlist); + + +$exccats = $users->getCategoryExclusionNames($userid); +$page->smarty->assign('exccats', implode(",", $exccats)); + +$page->smarty->assign('saburl', $sab->url); +$page->smarty->assign('sabapikey', $sab->apikey); + +$page->smarty->assign('nzbgeturl', $nzbget->url); +$page->smarty->assign('nzbgetusername', $nzbget->username); +$page->smarty->assign('nzbgetpassword', $nzbget->password); + + +$sabapikeytypes = array(SABnzbd::API_TYPE_NZB=>'Nzb Api Key', SABnzbd::API_TYPE_FULL=>'Full Api Key'); +if ($sab->apikeytype != "") + $page->smarty->assign('sabapikeytype', $sabapikeytypes[$sab->apikeytype]); + +$sabpriorities = array(SABnzbd::PRIORITY_FORCE=>'Force', SABnzbd::PRIORITY_HIGH=>'High', SABnzbd::PRIORITY_NORMAL=>'Normal', SABnzbd::PRIORITY_LOW=>'Low', SABnzbd::PRIORITY_PAUSED=>'Paused'); +if ($sab->priority != "") + $page->smarty->assign('sabpriority', $sabpriorities[$sab->priority]); + +$sabsettings = array(1=>'Site', 2=>'Cookie'); +$page->smarty->assign('sabsetting', $sabsettings[($sab->checkCookie()===true?2:1)]); + +$page->meta_title = "View User Profile"; +$page->meta_keywords = "view,profile,user,details"; +$page->meta_description = "View User Profile for ".$data["username"] ; + +$page->content = $page->smarty->fetch('profile.tpl'); +$page->render(); + diff --git a/lib/copy_this/www/pages/profileedit.php b/lib/copy_this/www/pages/profileedit.php index 069898c60..f0038e433 100644 --- a/lib/copy_this/www/pages/profileedit.php +++ b/lib/copy_this/www/pages/profileedit.php @@ -1,9 +1,6 @@ 0 && !endsWith($_POST['saburl'], "/")) + if (isset($_POST['saburl']) && strlen(trim($_POST['saburl'])) > 0 && !Utility::endsWith($_POST['saburl'], "/")) $_POST['saburl'] = $_POST['saburl'] . "/"; if ($_POST['password'] != "" && $_POST['password'] != $_POST['confirmpassword']) { diff --git a/lib/copy_this/www/pages/queue.php b/lib/copy_this/www/pages/queue.php index a5a5f3827..45a50e707 100644 --- a/lib/copy_this/www/pages/queue.php +++ b/lib/copy_this/www/pages/queue.php @@ -1,6 +1,4 @@ isLoggedIn()) { $page->show403(); diff --git a/lib/copy_this/www/pages/queuedata.php b/lib/copy_this/www/pages/queuedata.php new file mode 100644 index 000000000..0d50ad95b --- /dev/null +++ b/lib/copy_this/www/pages/queuedata.php @@ -0,0 +1,158 @@ +isLoggedIn()) + $page->show403(); + +$sab = new SABnzbd($page); +$nzbget = new NZBGet($page); + +if (empty($sab->url) && empty($sab->apikey) && empty($nzbget->url) && empty($nzbget->username)) + $page->show404(); + +$output = ""; +$reqtype = isset($_REQUEST["type"]) ? $_REQUEST["type"] : "queue"; + +switch ($reqtype) +{ + case "queue": + { + $json = $sab->getQueue(); + if ($json !== false) + { + $obj = json_decode($json); + $queue = $obj->{'jobs'}; + $count = 1; + + $speed = $obj->{'speed'}; + $queued = round($obj->{'mbleft'}, 2)."MB / ".round($obj->{'mb'}, 2)."MB"; + $status = ucwords(strtolower($obj->{'state'})); + + $output .= "

Download speed: ".$speed."B/s - Queued: ".$queued." - Status: ".$status."

"; + + if (count($queue) > 0) + { + $output.=""; + $output.=" + + + + + + + + "; + foreach ($queue as $item) + { + if (strpos($item->{'filename'}, "fetch NZB") > 0) + { + } + else + { + $output.=""; + $output.=""; + $output.=""; + $output.=""; + $output.=""; + $output.=""; + $output.=""; + $output.=""; + $output.=""; + $count++; + } + } + $output.="
Namesizeleft%time left
".$count."".htmlspecialchars($item->{'filename'}, ENT_QUOTES)."".round($item->{'mb'}, 2)." MB".round($item->{'mbleft'}, 2)." MB".($item->{'mb'}==0?0:round($item->{'mbleft'}/$item->{'mb'}*100))."%".$item->{'timeleft'}."delete
"; + } + else + { + $output.="

The queue is currently empty.

"; + } + } + else + { + $output.="

Error retreiving queue.

"; + } + + break; + } + case "history": + { + $json = $sab->getHistory(); + if ($json !== false) + { + $obj = json_decode($json); + $history = $obj->history->slots; + $count = 1; + + if (count($history) > 0) + { + $output.="

Download History

"; + $output.=""; + $output.=" + + + + + + + + "; + foreach ($history as $item) + { + $output.=""; + $output.=""; + $output.=""; + $output.=""; + $output.=""; + $output.=""; + $output.=""; + $output.=""; + $output.="\n"; + $count++; + } + $output.="
NameCategorystatussizedl timedate
".htmlspecialchars($item->{'name'}, ENT_QUOTES)."".htmlspecialchars($item->{'category'}, ENT_QUOTES)."".$item->{'status'}."".$item->{'size'}."".gmdate("H:i:s", $item->{'download_time'})."".gmdate("Y-m-d H:i", $item->{'completed'})."
"; + } + } + + break; + } + case "nzbget": + { + $queue = $nzbget->getQueue(); + if (is_array($queue) && count($queue) > 0) + { + $count = 1; + $output.=""; + $output.=" + + + + + + + + "; + foreach ($queue as $item) + { + $output.=""; + $output.=""; + $output.=""; + $output.=""; + $output.=""; + $output.=""; + $output.=""; + $output.=""; + $output.=""; + $count++; + } + $output.="
Namesizeleft%left
".$count."".htmlspecialchars($item['NZBNicename'], ENT_QUOTES)."".round($item['FileSizeMB'], 2)." MB".round($item['RemainingSizeMB'], 2)." MB".($item['FileSizeMB']==0?0:round($item['RemainingSizeMB']/$item['FileSizeMB']*100))."%".$item['RemainingFileCount']."delete
"; + } + else + { + $output.="

The queue is currently empty.

"; + } + + break; + } +} + +print $output; diff --git a/lib/copy_this/www/pages/register.php b/lib/copy_this/www/pages/register.php index be1b696ec..1c1e5ad51 100644 --- a/lib/copy_this/www/pages/register.php +++ b/lib/copy_this/www/pages/register.php @@ -1,5 +1,4 @@ isLoggedIn()) $page->show404(); @@ -20,7 +19,6 @@ elseif ($page->site->registerstatus == Sites::REGISTER_STATUS_INVITE && (!isset( // Use recaptcha? if ($page->site->registerrecaptcha == 1) { - require_once(WWW_DIR."/lib/recaptchalib.php"); $page->smarty->assign('recaptcha', recaptcha_get_html($page->site->recaptchapublickey, null, $page->secure_connection)); } diff --git a/lib/copy_this/www/pages/rss.php b/lib/copy_this/www/pages/rss.php new file mode 100644 index 000000000..c8eb309c0 --- /dev/null +++ b/lib/copy_this/www/pages/rss.php @@ -0,0 +1,137 @@ +isLoggedIn()) + $page->show403(); + + $page->title = "Rss Feeds"; + $page->meta_title = "Rss Nzb Feeds"; + $page->meta_keywords = "view,nzb,description,details,rss,atom"; + $page->meta_description = "View available Rss Nzb feeds."; + + $categorylist = $category->get(true, $page->userdata["categoryexclusions"]); + $page->smarty->assign('categorylist',$categorylist); + + $parentcategorylist = $category->getForMenu($page->userdata["categoryexclusions"]); + $page->smarty->assign('parentcategorylist',$parentcategorylist); + + $page->content = $page->smarty->fetch('rssdesc.tpl'); + $page->render(); + +} +// +// user requested a feed, ensure either logged in or passing a valid token +// +else +{ + $uid = -1; + $rsstoken = -1; + if (!$users->isLoggedIn()) + { + if (!isset($_GET["i"]) || !isset($_GET["r"])) + $page->show403(); + + $res = $users->getByIdAndRssToken($_GET["i"], $_GET["r"]); + if (!$res) + $page->show403(); + + $uid = $_GET["i"]; + $rsstoken = $_GET["r"]; + $maxrequests = $res['apirequests']; + } + else + { + $uid = $page->userdata["ID"]; + $rsstoken = $page->userdata["rsstoken"]; + $maxrequests = $page->userdata['apirequests']; + } + + // + // A hash of the users ip to record against the api hit + // + $hosthash = ""; + if ($page->site->storeuserips == 1) + $hosthash = $users->getHostHash($_SERVER["REMOTE_ADDR"], $page->site->siteseed); + + $apirequests = $users->getApiRequests($uid); + if ($apirequests['num'] > $maxrequests) + { + $page->show429($apirequests['nextrequest']); + } else { + $users->addApiRequest($uid, $_SERVER['REQUEST_URI'], $hosthash); + } + + // + // valid or logged in user, get them the requested feed + // + if (isset($_GET["dl"]) && $_GET["dl"] == "1") + $page->smarty->assign("dl","1"); + + $usercat = -1; + if (isset($_GET["t"])) + $usercat = ($_GET["t"]==0 ? -1 : $_GET["t"]); + + $userrage = -1; + $useranidb = -1; + $userseries = -1; + if (isset($_GET["rage"])) + { + $userrage = ($_GET["rage"]==0 ? -1 : $_GET["rage"]+0); + } elseif (isset($_GET["anidb"])) { + $useranidb = ($_GET["anidb"]==0 ? -1 : $_GET["anidb"]+0); + } + + $usernum = 100; + if (isset($_GET["num"])) + $usernum = $_GET["num"]+0; + + if (isset($_GET["del"]) && $_GET["del"] == "1") + $page->smarty->assign("del","1"); + + $userairdate = -1; + if (isset($_GET["airdate"])) + $userairdate = $_GET["airdate"]+0; + + $page->smarty->assign('uid',$uid); + $page->smarty->assign('rsstoken',$rsstoken); + + if ($usercat == -3) + { + $page->smarty->assign('rsstitle',"My Shows Feed"); + $catexclusions = $users->getCategoryExclusion($uid); + $reldata = $releases->getShowsRss($usernum, $uid, $catexclusions, $userairdate); + } + elseif ($usercat == -4) + { + $page->smarty->assign('rsstitle',"My Movies Feed"); + $catexclusions = $users->getCategoryExclusion($uid); + $reldata = $releases->getMyMoviesRss($usernum, $uid, $catexclusions); + } + else + { + if ($usercat == -2) + $page->smarty->assign('rsstitle',"My Cart Feed"); + + $reldata = $releases->getRss(explode(",",$usercat), $usernum, $uid, $userrage, $useranidb, $userairdate); + } + $page->smarty->assign('releases',$reldata); + header("Content-type: text/xml"); + + $page->smarty->assign('rsshead',$page->smarty->fetch('rssheader.tpl')); + echo trim($page->smarty->fetch('rss.tpl')); + +} \ No newline at end of file diff --git a/lib/copy_this/www/pages/search.php b/lib/copy_this/www/pages/search.php index 17b5fb3b0..0c4f7dc32 100644 --- a/lib/copy_this/www/pages/search.php +++ b/lib/copy_this/www/pages/search.php @@ -1,8 +1,4 @@ isLoggedIn()) { diff --git a/lib/copy_this/www/pages/sendtonzbget.php b/lib/copy_this/www/pages/sendtonzbget.php new file mode 100644 index 000000000..82d528930 --- /dev/null +++ b/lib/copy_this/www/pages/sendtonzbget.php @@ -0,0 +1,24 @@ +isLoggedIn()) + $page->show403(); + +if (empty($_GET["id"])) + $page->show404(); + +$nzbget = new NZBGet($page); + +if (empty($nzbget->url)) + $page->show404(); + +if (empty($nzbget->username)) + $page->show404(); + +if (empty($nzbget->password)) + $page->show404(); + +$guid = $_GET["id"]; + +$nzbget->sendToNZBGet($guid); + diff --git a/lib/copy_this/www/pages/sendtoqueue.php b/lib/copy_this/www/pages/sendtoqueue.php index c8b512f12..11db9998c 100644 --- a/lib/copy_this/www/pages/sendtoqueue.php +++ b/lib/copy_this/www/pages/sendtoqueue.php @@ -1,6 +1,4 @@ isLoggedIn()) { $page->show403(); diff --git a/lib/copy_this/www/pages/sendtosab.php b/lib/copy_this/www/pages/sendtosab.php new file mode 100644 index 000000000..e810f3930 --- /dev/null +++ b/lib/copy_this/www/pages/sendtosab.php @@ -0,0 +1,20 @@ +isLoggedIn()) + $page->show403(); + +if (empty($_GET["id"])) + $page->show404(); + +$sab = new SABnzbd($page); + +if (empty($sab->url)) + $page->show404(); + +if (empty($sab->apikey)) + $page->show404(); + +$guid = $_GET["id"]; + +$sab->sendToSab($guid); + diff --git a/lib/copy_this/www/pages/series.php b/lib/copy_this/www/pages/series.php index 34bd8603b..351070bae 100644 --- a/lib/copy_this/www/pages/series.php +++ b/lib/copy_this/www/pages/series.php @@ -1,8 +1,4 @@ isLoggedIn()) { $page->show403(); diff --git a/lib/copy_this/www/pages/sitemap.php b/lib/copy_this/www/pages/sitemap.php new file mode 100644 index 000000000..b0424b943 --- /dev/null +++ b/lib/copy_this/www/pages/sitemap.php @@ -0,0 +1,85 @@ +smarty; + +$arPages = array(); + +$arPages[] = buildURL("Home", "Home Page", "/", 'daily', '1.0'); + + +$role=0; +if ($page->userdata != null) + $role = $page->userdata["role"]; + +// +// useful links +// +$contents = new Contents(); +$contentlist = $contents->getForMenuByTypeAndRole(Contents::TYPEUSEFUL, $role); +foreach ($contentlist as $content) +{ + $arPages[] = buildURL("Useful Links", $content["title"], '/content/'.$content["id"].$content["url"], 'monthly', '0.50'); +} + +// +// articles +// +$contentlist = $contents->getForMenuByTypeAndRole(Contents::TYPEARTICLE, $role); +foreach ($contentlist as $content) +{ + $arPages[] = buildURL("Articles", $content["title"], '/content/'.$content["id"].$content["url"], 'monthly', '0.50'); +} + +// +// static pages +// +$arPages[] = buildURL("Useful Links", "Contact Us", "/contact-us", 'yearly', '0.30'); +$arPages[] = buildURL("Useful Links", "Site Map", "/sitemap", 'weekly', '0.50'); + +if ($page->userdata != null) +{ + $arPages[] = buildURL("Useful Links", "Rss Feeds", "/rss", 'weekly', '0.50'); + $arPages[] = buildURL("Useful Links", "API", "/apihelp", 'weekly', '0.50'); + + $arPages[] = buildURL("Nzb", "Search Nzb", "/search", 'weekly', '0.50'); + $arPages[] = buildURL("Nzb", "Search Raw", "/searchraw", 'daily', '0.80'); + $arPages[] = buildURL("Nzb", "Browse Nzb", "/browse", 'daily', '0.80'); + $arPages[] = buildURL("Nzb", "Browse Groups", "/browsegroup", 'daily', '0.80'); + $arPages[] = buildURL("Nzb", "Movies", "/movies", 'daily', '0.80'); + $arPages[] = buildURL("Nzb", "TV Series", "/series", 'daily', '0.80'); + $arPages[] = buildURL("Nzb", "Anime", "/anime", 'daily', '0.80'); + $arPages[] = buildURL("Nzb", "Music", "/music", 'daily', '0.80'); + $arPages[] = buildURL("Nzb", "Console", "/console", 'daily', '0.80'); + + $arPages[] = buildURL("Forum", "Forum", "/forum", 'daily', '0.80'); + + $arPages[] = buildURL("User", "Cart", "/cart", 'weekly', '0.50'); + $arPages[] = buildURL("User", "Profile", "/profile", 'weekly', '0.50'); +} + +// +// echo appropriate site map +// +asort($arPages); +$page->smarty->assign('sitemaps',$arPages); + +if (isset($_GET["type"]) && $_GET["type"] == "xml") +{ + echo $page->smarty->fetch('sitemap-xml.tpl'); +} +else +{ + $page->title = $page->site->title. " site map"; + $page->meta_title = $page->site->title. " site map"; + $page->meta_keywords = "sitemap,site,map"; + $page->meta_description = $page->site->title." site map shows all our pages."; + $page->content = $page->smarty->fetch('sitemap.tpl'); + $page->render(); +} + +function buildURL($type, $name, $url, $freq='daily', $p='1.0') +{ + $s = new Sitemap($type, $name, $url, $freq, $p); + return $s; +} + diff --git a/lib/copy_this/www/pages/terms-and-conditions.php b/lib/copy_this/www/pages/terms-and-conditions.php new file mode 100644 index 000000000..8c77715a8 --- /dev/null +++ b/lib/copy_this/www/pages/terms-and-conditions.php @@ -0,0 +1,11 @@ +title = "Terms and Conditions"; +$page->meta_title = $page->site->title." - Terms and conditions"; +$page->meta_keywords = "terms,conditions"; +$page->meta_description = "Terms and Conditions for ".$page->site->title; + +$page->content = $page->smarty->fetch('terms.tpl'); + +$page->render(); + diff --git a/lib/copy_this/www/pages/upcoming.php b/lib/copy_this/www/pages/upcoming.php index 6b63f55c1..7d3a115f4 100644 --- a/lib/copy_this/www/pages/upcoming.php +++ b/lib/copy_this/www/pages/upcoming.php @@ -1,5 +1,5 @@ isLoggedIn()) { $page->show403(); } diff --git a/lib/copy_this/www/pages/xxx.php b/lib/copy_this/www/pages/xxx.php index 65cf90fe3..e21d2d066 100644 --- a/lib/copy_this/www/pages/xxx.php +++ b/lib/copy_this/www/pages/xxx.php @@ -1,6 +1,4 @@ isLoggedIn()) { $page->show403(); diff --git a/lib/copy_this/www/pages/xxxmodal.php b/lib/copy_this/www/pages/xxxmodal.php index fa26e0724..c18360cea 100644 --- a/lib/copy_this/www/pages/xxxmodal.php +++ b/lib/copy_this/www/pages/xxxmodal.php @@ -1,5 +1,4 @@ users->isLoggedIn()) { $page->show403(); diff --git a/lib/copy_this/www/robots.txt b/lib/copy_this/www/robots.txt new file mode 100644 index 000000000..77470cb39 --- /dev/null +++ b/lib/copy_this/www/robots.txt @@ -0,0 +1,2 @@ +User-agent: * +Disallow: / \ No newline at end of file diff --git a/lib/copy_this/www/templates/nntmux/scripts/utils.js b/lib/copy_this/www/templates/nntmux/scripts/utils.js index 540927fc3..6ece66f3e 100644 --- a/lib/copy_this/www/templates/nntmux/scripts/utils.js +++ b/lib/copy_this/www/templates/nntmux/scripts/utils.js @@ -427,7 +427,7 @@ jQuery(function ($) { }, position: { my: 'top right', - at: 'bottom left', + at: 'bottom left' }, style: { classes: 'qtip-dark qtip-shadow qtip-rounded', diff --git a/lib/copy_this/www/templates/nntmux/views/frontend/movies.tpl b/lib/copy_this/www/templates/nntmux/views/frontend/movies.tpl index 3dde6d9ae..7a7ac12a1 100644 --- a/lib/copy_this/www/templates/nntmux/views/frontend/movies.tpl +++ b/lib/copy_this/www/templates/nntmux/views/frontend/movies.tpl @@ -131,7 +131,7 @@ true]))->checkPre((isset($argv[1]) && is_numeric($argv[1]) ? $argv[1] : false)); \ No newline at end of file diff --git a/lib/removeCrapReleases.php b/lib/removeCrapReleases.php index 973ba512d..915a9b237 100644 --- a/lib/removeCrapReleases.php +++ b/lib/removeCrapReleases.php @@ -4,9 +4,6 @@ * This script deletes releases that match certain criteria, type php removeCrapReleases.php false for details. */ -require_once(dirname(__FILE__)."/../bin/config.php"); -require_once(WWW_DIR . "/lib/ColorCLI.php"); -require_once("ReleaseRemover.php"); $cli = new \ColorCLI(); $n = PHP_EOL; diff --git a/lib/requestid.php b/lib/requestid.php index 93698ae10..4125c09d1 100644 --- a/lib/requestid.php +++ b/lib/requestid.php @@ -1,8 +1,4 @@ log->error("\nThis script renames all table columns to lowercase, it can be dangerous. Please BACKUP your database before running this script.\n" diff --git a/lib/testing/DB/reset_postprocessing.php b/lib/testing/DB/reset_postprocessing.php index b759ba643..3353da3d3 100644 --- a/lib/testing/DB/reset_postprocessing.php +++ b/lib/testing/DB/reset_postprocessing.php @@ -1,8 +1,7 @@ $pdo->log]); diff --git a/lib/testing/DB/reset_truncate.php b/lib/testing/DB/reset_truncate.php index fa4d8c97b..a88bb3309 100644 --- a/lib/testing/DB/reset_truncate.php +++ b/lib/testing/DB/reset_truncate.php @@ -1,8 +1,8 @@ true, 'Settings' => $pdo]); diff --git a/lib/testing/PostProc/getImdb.php b/lib/testing/PostProc/getImdb.php index 4d74cce4a..4152eba7d 100644 --- a/lib/testing/PostProc/getImdb.php +++ b/lib/testing/PostProc/getImdb.php @@ -1,9 +1,7 @@ diff --git a/lib/testing/_run_once/tpg_fixes.php b/lib/testing/_run_once/tpg_fixes.php index 19e083c17..1ea2ea8fe 100644 --- a/lib/testing/_run_once/tpg_fixes.php +++ b/lib/testing/_run_once/tpg_fixes.php @@ -27,8 +27,8 @@ if (!isset($argv[1]) || !in_array($argv[1], ['1'])) { } require_once(dirname(__FILE__) . "/../../../bin/config.php"); -require_once(WWW_DIR . "/lib/framework/db.php"); -require_once(WWW_DIR . "/lib/site.php"); + +use newznab\db\DB; $pdo = new DB(); $s = new Sites(); diff --git a/lib/testing/nzb-import.php b/lib/testing/nzb-import.php index cc7978181..39af8e07e 100644 --- a/lib/testing/nzb-import.php +++ b/lib/testing/nzb-import.php @@ -1,6 +1,4 @@ log->info("\nAnalyzing your tables to refresh your indexes.")); $pdo->optimise(false, 'analyze', false, ['releases']); -passthru('clear'); +Utility::clearScreen(); $runVar['settings']['monitor'] = 0; $runVar['counts']['iterations'] = 1; diff --git a/run.php b/run.php index 18bfce027..dc5fdd29a 100644 --- a/run.php +++ b/run.php @@ -1,10 +1,7 @@ queryOneRow('SELECT enabled, posting, fetching FROM sharing'); $t = new \Tmux(); $tmux = $t->get(); diff --git a/scripts/reset_rar_check.php b/scripts/reset_rar_check.php index 5041290e8..f1d4c1cc3 100755 --- a/scripts/reset_rar_check.php +++ b/scripts/reset_rar_check.php @@ -1,7 +1,6 @@ query("update releases set passwordstatus = -1 where rarinnerfilecount = 0"); diff --git a/start.php b/start.php index 62a504177..5cce5f2f7 100644 --- a/start.php +++ b/start.php @@ -6,11 +6,9 @@ * * It will start the tmux server and monitoring scripts if needed. */ -require_once(dirname(__FILE__)."/bin/config.php"); -require_once(WWW_DIR . "lib/framework/db.php"); -require_once(WWW_DIR. '/lib/Tmux.php'); +use newznab\db\DB; -$pdo = new DB(); +$pdo = new newznab\db\DB(); $tmux = new \Tmux(); $tmux_settings = $tmux->get(); diff --git a/stop.php b/stop.php index 246035411..14fd6bfda 100644 --- a/stop.php +++ b/stop.php @@ -1,6 +1,3 @@ stopIfRunning(); diff --git a/threaded_scripts_readme.txt b/threaded_scripts_readme.txt deleted file mode 100644 index fcab247ac..000000000 --- a/threaded_scripts_readme.txt +++ /dev/null @@ -1,19 +0,0 @@ -# For the threaded scripts you will require the Python cymysql module for mysql: - # Python 2.* - sudo apt-get install python-setuptools python-pip - sudo python -m easy_install pip - sudo easy_install cymysql - sudo easy_install pynntp - sudo easy_install socketpool - pip list - # Python 3.* - If Python 3 is installed, the module also must be installed - sudo apt-get install python3-setuptools python3-pip - sudo python3 -m easy_install pip - sudo pip-3.2 install cymysql - sudo pip-3.2 install pynntp - sudo pip-3.2 install socketpool - pip-3.2 list - # -or- - sudo pip-3.3 install cymysql - pip-3.3 list - #For Ubuntu 13.10, python3 uses pip3, not pip3.2 \ No newline at end of file